1
0

UploadHelper.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using Admin.Core.Common.Attributes;
  2. using Admin.Core.Common.Configs;
  3. using Admin.Core.Common.Output;
  4. using Microsoft.AspNetCore.Http;
  5. using System;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using FileInfo = Admin.Core.Common.Files.FileInfo;
  11. namespace Admin.Core.Common.Helpers
  12. {
  13. /// <summary>
  14. /// 文件上传帮助类
  15. /// </summary>
  16. [SingleInstance]
  17. public class UploadHelper
  18. {
  19. /// <summary>
  20. /// 上传单文件
  21. /// </summary>
  22. /// <param name="file"></param>
  23. /// <param name="config"></param>
  24. /// <param name="args"></param>
  25. /// <param name="cancellationToken"></param>
  26. /// <returns></returns>
  27. public async Task<IResponseOutput<FileInfo>> UploadAsync(IFormFile file, FileUploadConfig config, object args, CancellationToken cancellationToken = default)
  28. {
  29. var res = new ResponseOutput<FileInfo>();
  30. if (file == null || file.Length < 1)
  31. {
  32. return res.NotOk("请上传文件!");
  33. }
  34. //格式限制
  35. if (!config.ContentType.Contains(file.ContentType))
  36. {
  37. return res.NotOk("文件格式错误");
  38. }
  39. //大小限制
  40. if (!(file.Length <= config.MaxSize))
  41. {
  42. return res.NotOk("文件过大");
  43. }
  44. var fileInfo = new FileInfo(file.FileName, file.Length)
  45. {
  46. UploadPath = config.UploadPath,
  47. RequestPath = config.RequestPath
  48. };
  49. var dateTimeFormat = config.DateTimeFormat.NotNull() ? DateTime.Now.ToString(config.DateTimeFormat) : "";
  50. var format = config.Format.NotNull() ? StringHelper.Format(config.Format, args) : "";
  51. fileInfo.RelativePath = Path.Combine(dateTimeFormat, format).ToPath();
  52. if (!Directory.Exists(fileInfo.FileDirectory))
  53. {
  54. Directory.CreateDirectory(fileInfo.FileDirectory);
  55. }
  56. fileInfo.SaveName = $"{IdWorkerHelper.GenId64()}.{fileInfo.Extension}";
  57. await SaveAsync(file, fileInfo.FilePath, cancellationToken);
  58. return res.Ok(fileInfo);
  59. }
  60. /// <summary>
  61. /// 保存文件
  62. /// </summary>
  63. /// <param name="file"></param>
  64. /// <param name="filePath"></param>
  65. /// <param name="cancellationToken"></param>
  66. /// <returns></returns>
  67. public async Task SaveAsync(IFormFile file, string filePath, CancellationToken cancellationToken = default)
  68. {
  69. using (var stream = new FileStream(filePath, FileMode.Create))
  70. {
  71. await file.CopyToAsync(stream, cancellationToken);
  72. }
  73. }
  74. }
  75. }