ImgController.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Threading.Tasks;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Options;
  5. using Admin.Core.Common.Output;
  6. using Admin.Core.Attributes;
  7. using Admin.Core.Common.Helpers;
  8. using Admin.Core.Common.Configs;
  9. using Admin.Core.Common.Auth;
  10. namespace Admin.Core.Controllers.Admin
  11. {
  12. /// <summary>
  13. /// 图片管理
  14. /// </summary>
  15. public class ImgController : AreaController
  16. {
  17. private readonly IUser _user;
  18. private readonly UploadConfig _uploadConfig;
  19. private readonly UploadHelper _uploadHelper;
  20. public ImgController(
  21. IUser user,
  22. IOptionsMonitor<UploadConfig> uploadConfig,
  23. UploadHelper uploadHelper
  24. )
  25. {
  26. _user = user;
  27. _uploadConfig = uploadConfig.CurrentValue;
  28. _uploadHelper = uploadHelper;
  29. }
  30. /*
  31. /// <summary>
  32. /// 获取头像
  33. /// </summary>
  34. /// <param name="environment"></param>
  35. /// <param name="fileName"></param>
  36. /// <returns></returns>
  37. [HttpGet]
  38. [Route("{fileName}")]
  39. [NoOprationLog]
  40. [AllowAnonymous]
  41. public FileStreamResult Avatar([FromServices]IWebHostEnvironment environment, string fileName = "")
  42. {
  43. string filePath = Path.Combine(environment.WebRootPath,"avatar", fileName).ToPath();
  44. var stream = System.IO.File.OpenRead(filePath);
  45. string fileExt = Path.GetExtension(filePath);
  46. var contentTypeProvider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
  47. var contentType = contentTypeProvider.Mappings[fileExt];
  48. var fileDownloadName = Path.GetFileName(filePath);
  49. return File(stream, contentType, fileDownloadName);
  50. }
  51. */
  52. /// <summary>
  53. /// 上传头像
  54. /// </summary>
  55. /// <param name="file"></param>
  56. /// <returns></returns>
  57. [HttpPost]
  58. [Login]
  59. public async Task<IResponseOutput> AvatarUpload([FromForm]IFormFile file)
  60. {
  61. var config = _uploadConfig.Avatar;
  62. var res = await _uploadHelper.UploadAsync(file, config, new { _user.Id });
  63. if (res.Success)
  64. {
  65. return ResponseOutput.Ok(res.Data.FileRelativePath);
  66. }
  67. return ResponseOutput.NotOk("上传失败!");
  68. }
  69. }
  70. }