平安校园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileService.cs 9.5 KiB

4 kuukautta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. 
  2. //
  3. namespace SafeCampus.System;
  4. /// <summary>
  5. /// <inheritdoc cref="IFileService"/>
  6. /// </summary>
  7. public class FileService : DbRepository<SysFile>, IFileService
  8. {
  9. private readonly IConfigService _configService;
  10. public FileService(IConfigService configService)
  11. {
  12. _configService = configService;
  13. }
  14. /// <inheritdoc/>
  15. public async Task<SqlSugarPagedList<SysFile>> Page(FilePageInput input)
  16. {
  17. var query = Context.Queryable<SysFile>().WhereIF(!string.IsNullOrEmpty(input.Engine), it => it.Engine == input.Engine)//根据关键字查询
  18. .WhereIF(!string.IsNullOrEmpty(input.SearchKey), it => it.Name.Contains(input.SearchKey))//根据关键字查询
  19. .OrderByIF(!string.IsNullOrEmpty(input.SortField), $"{input.SortField} {input.SortOrder}")//排序
  20. .OrderBy(it => it.Id);
  21. var pageInfo = await query.ToPagedListAsync(input.PageNum, input.PageSize);//分页
  22. return pageInfo;
  23. }
  24. /// <inheritdoc/>
  25. public async Task<long> UploadFile(string engine, IFormFile file)
  26. {
  27. return await StorageFile(engine, file);
  28. }
  29. /// <inheritdoc/>
  30. public async Task Delete(BaseIdListInput input)
  31. {
  32. var ids = input.Ids;//获取ID
  33. await DeleteByIdsAsync(ids.Cast<object>().ToArray());//根据ID删除数据库
  34. }
  35. /// <inheritdoc/>
  36. public FileStreamResult GetFileStreamResult(string path, string fileName, bool isPathFolder = false)
  37. {
  38. if (isPathFolder) path = path.CombinePath(fileName);
  39. fileName = HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("UTF-8"));//文件名转utf8不然前端下载会乱码
  40. //文件转流
  41. var result = new FileStreamResult(new FileStream(path, FileMode.Open), "application/octet-stream")
  42. {
  43. FileDownloadName = fileName
  44. };
  45. return result;
  46. }
  47. public async Task<FileStreamResult> GetFileStreamResultFromMinio(string objectName, string fileName)
  48. {
  49. var minioService = App.GetService<MinioUtils>();
  50. var stream = await minioService.DownloadFileAsync(objectName);
  51. fileName = HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("UTF-8"));//文件名转utf8不然前端下载会乱码
  52. //文件转流
  53. var result = new FileStreamResult(stream, "application/octet-stream")
  54. {
  55. FileDownloadName = fileName
  56. };
  57. return result;
  58. }
  59. /// <inheritdoc/>
  60. public FileStreamResult GetFileStreamResult(byte[] byteArray, string fileName)
  61. {
  62. fileName = HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("UTF-8"));//文件名转utf8不然前端下载会乱码
  63. //文件转流
  64. var result = new FileStreamResult(new MemoryStream(byteArray), "application/octet-stream")
  65. {
  66. FileDownloadName = fileName
  67. };
  68. return result;
  69. }
  70. /// <inheritdoc/>
  71. public async Task<FileStreamResult> Download(BaseIdInput input)
  72. {
  73. var devFile = await GetByIdAsync(input.Id);
  74. if (devFile != null)
  75. {
  76. if (devFile.Engine == SysDictConst.FILE_ENGINE_LOCAL)
  77. return GetFileStreamResult(devFile.StoragePath, devFile.Name);
  78. if (devFile.Engine == SysDictConst.FILE_ENGINE_MINIO)
  79. return await GetFileStreamResultFromMinio(devFile.ObjName, devFile.Name);
  80. return null;
  81. }
  82. return null;
  83. }
  84. #region 方法
  85. /// <summary>
  86. /// 存储文件
  87. /// </summary>
  88. /// <param name="engine"></param>
  89. /// <param name="file"></param>
  90. private async Task<long> StorageFile(string engine, IFormFile file)
  91. {
  92. var bucketName = string.Empty;// 存储桶名称
  93. var storageUrl = string.Empty;// 定义存储的url,本地文件返回文件实际路径,其他引擎返回网络地址
  94. var objName = string.Empty;// 定义存储的url,本地文件返回文件实际路径,其他引擎返回网络地址
  95. var objectId = CommonUtils.GetSingleId();//生成id
  96. switch (engine)
  97. {
  98. //存储本地
  99. case SysDictConst.FILE_ENGINE_LOCAL:
  100. bucketName = "defaultBucketName";// 存储桶名称
  101. storageUrl = await StorageLocal(objectId, file);
  102. break;
  103. //存储本地
  104. case SysDictConst.FILE_ENGINE_MINIO:
  105. var config = await _configService.GetByConfigKey(CateGoryConst.CONFIG_FILE_MINIO, SysConfigConst.FILE_MINIO_DEFAULT_BUCKET_NAME);
  106. if (config != null)
  107. {
  108. bucketName = config.ConfigValue;// 存储桶名称
  109. (objName, storageUrl) = await StorageMinio(objectId, file);
  110. }
  111. break;
  112. default:
  113. throw Oops.Bah("不支持的文件引擎");
  114. }
  115. var fileSizeKb = (long)(file.Length / 1024.0);// 文件大小KB
  116. var fileSuffix = Path.GetExtension(file.FileName).ToLower();// 文件后缀
  117. var devFile = new SysFile
  118. {
  119. Id = objectId,
  120. Engine = engine,
  121. Bucket = bucketName,
  122. Name = file.FileName,
  123. Suffix = fileSuffix.Split(".")[1],
  124. ObjName = objName,
  125. SizeKb = fileSizeKb,
  126. SizeInfo = GetSizeInfo(fileSizeKb),
  127. StoragePath = storageUrl
  128. };
  129. if (engine != CateGoryConst.CONFIG_FILE_LOCAL)//如果不是本地,设置下载地址
  130. {
  131. devFile.DownloadPath = storageUrl;
  132. }
  133. //如果是图片,生成缩略图
  134. if (IsPic(fileSuffix))
  135. {
  136. //$"data:image/png;base64," + imgByte;
  137. await using var fileStream = file.OpenReadStream();//获取文件流
  138. var image = SKImage.FromEncodedData(fileStream);//获取图片
  139. var bmp = SKBitmap.FromImage(image);
  140. var thubnail = bmp.GetPicThumbnail(100, 100);//压缩图片
  141. var thubnailBase64 = ImageUtil.ImgToBase64String(thubnail);//转base64
  142. devFile.Thumbnail = "data:image/png;base64," + thubnailBase64;
  143. }
  144. await InsertAsync(devFile);
  145. return objectId;
  146. }
  147. /// <summary>
  148. /// 存储本地文件
  149. /// </summary>
  150. /// <param name="fileId"></param>
  151. /// <param name="file"></param>
  152. private async Task<string> StorageLocal(long fileId, IFormFile file)
  153. {
  154. string uploadFileFolder;
  155. var configKey = string.Empty;
  156. //判断是windows还是linux
  157. if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  158. {
  159. configKey = SysConfigConst.FILE_LOCAL_FOLDER_FOR_UNIX;//Linux
  160. }
  161. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  162. {
  163. configKey = SysConfigConst.FILE_LOCAL_FOLDER_FOR_WINDOWS;//Windows
  164. }
  165. //获取路径配置
  166. var config = await _configService.GetByConfigKey(CateGoryConst.CONFIG_FILE_LOCAL, configKey);
  167. if (config != null)
  168. {
  169. uploadFileFolder = config.ConfigValue;//赋值路径
  170. var now = DateTime.Now.ToString("d");
  171. var filePath = Path.Combine(uploadFileFolder, now);
  172. if (!Directory.Exists(filePath))//如果不存在就创建文件夹
  173. Directory.CreateDirectory(filePath);
  174. var fileSuffix = Path.GetExtension(file.FileName).ToLower();// 文件后缀
  175. var fileObjectName = $"{fileId}{fileSuffix}";//存储后的文件名
  176. var fileName = Path.Combine(filePath, fileObjectName);//获取文件全路局
  177. fileName = fileName.Replace("\\", "/");//格式化一系
  178. //存储文件
  179. using (var stream = File.Create(Path.Combine(filePath, fileObjectName)))
  180. {
  181. await file.CopyToAsync(stream);
  182. }
  183. return fileName;
  184. }
  185. throw Oops.Oh("文件存储路径未配置");
  186. }
  187. /// <summary>
  188. /// 存储到minio
  189. /// </summary>
  190. /// <param name="fileId"></param>
  191. /// <param name="file"></param>
  192. /// <returns></returns>
  193. private async Task<(string objName, string downloadUrl)> StorageMinio(long fileId, IFormFile file)
  194. {
  195. var minioService = App.GetService<MinioUtils>();
  196. var now = DateTime.Now.ToString("d");
  197. var fileSuffix = Path.GetExtension(file.FileName).ToLower();// 文件后缀
  198. var fileObjectName = $"{now}/{fileId}{fileSuffix}";//存储后的文件名
  199. var downloadUrl = await minioService.PutObjectAsync(fileObjectName, file);
  200. return (fileObjectName, downloadUrl);
  201. }
  202. /// <summary>
  203. /// 获取文件大小
  204. /// </summary>
  205. /// <param name="fileSizeKb"></param>
  206. /// <returns></returns>
  207. private string GetSizeInfo(long fileSizeKb)
  208. {
  209. var b = fileSizeKb * 1024;
  210. const int mb = 1024 * 1024;
  211. const int kb = 1024;
  212. if (b / mb >= 1)
  213. {
  214. return Math.Round(b / (float)mb, 2) + "MB";
  215. }
  216. if (b / kb >= 1)
  217. {
  218. return Math.Round(b / (float)kb, 2) + "KB";
  219. }
  220. if (b == 0)
  221. {
  222. return "0B";
  223. }
  224. return null;
  225. }
  226. /// <summary>
  227. /// 判断是否是图片
  228. /// </summary>
  229. /// <param name="suffix">后缀名</param>
  230. /// <returns></returns>
  231. private bool IsPic(string suffix)
  232. {
  233. //图片后缀名列表
  234. var pics = new[]
  235. {
  236. ".png", ".bmp", ".gif", ".jpg", ".jpeg", ".psd"
  237. };
  238. if (pics.Contains(suffix))
  239. return true;
  240. return false;
  241. }
  242. #endregion 方法
  243. }