AdminFileController.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.IO;
  2. using System.Threading.Tasks;
  3. using GxPress.Common.Exceptions;
  4. using GxPress.Common.Tools;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.AspNetCore.Mvc;
  8. namespace GxPress.Api.AdminControllers
  9. {
  10. /// <summary>
  11. /// 文件管理
  12. /// </summary>
  13. [Route("api/admin/file")]
  14. [ApiController]
  15. public class AdminFileController : ControllerBase
  16. {
  17. private readonly IWebHostEnvironment _environment;
  18. public AdminFileController(IWebHostEnvironment environment)
  19. {
  20. _environment = environment;
  21. }
  22. /// <summary>
  23. /// 上传
  24. /// </summary>
  25. /// <param name="file"></param>
  26. /// <returns></returns>
  27. [HttpPost("upload")]
  28. public async Task<ResultPath> Upload(IFormFile file)
  29. {
  30. if (file == null) throw new BusinessException("请选择需要上传的文件");
  31. byte[] bytes;
  32. await using (var ms = new MemoryStream())
  33. {
  34. file.CopyTo(ms);
  35. bytes = ms.ToArray();
  36. }
  37. var saveResult = FileHelper.SaveFile(StringUtils.GetWebRootPath(_environment.WebRootPath), file.FileName,
  38. bytes);
  39. saveResult.AbsolutePath = Request.Scheme + "://" + Request.Host.Host +
  40. (Request.Host.Port > 0 ? $":{Request.Host.Port}" : string.Empty) +
  41. saveResult.RelativePath;
  42. return saveResult;
  43. }
  44. //上传文件到本地缓存文件夹,返回一个预览地址
  45. //真正提交的时候把缓存文件异步保存到七牛云
  46. //下载,从七牛云下载文件?
  47. /// <summary>
  48. /// 上传用户Excel
  49. /// </summary>
  50. /// <returns></returns>
  51. [HttpPost("upload-user-excel")]
  52. public async Task<ResultPath> UploadUserExcel(IFormFile file)
  53. {
  54. if (file == null) throw new BusinessException("请选择需要上传的文件");
  55. byte[] bytes;
  56. await using (var ms = new MemoryStream())
  57. {
  58. file.CopyTo(ms);
  59. bytes = ms.ToArray();
  60. }
  61. var saveResult = FileHelper.SaveFile(StringUtils.GetWebRootPath(_environment.WebRootPath), file.FileName,
  62. bytes);
  63. saveResult.AbsolutePath = Request.Scheme + "://" + Request.Host.Host +
  64. (Request.Host.Port > 0 ? $":{Request.Host.Port}" : string.Empty) +
  65. saveResult.RelativePath;
  66. return saveResult;
  67. }
  68. }
  69. }