UploadController.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Bowin.Common.Files;
  7. using Bowin.Common.JSON;
  8. using Bowin.Common.Utility;
  9. using Microsoft.AspNetCore.Authorization;
  10. using Microsoft.AspNetCore.Http;
  11. using Microsoft.AspNetCore.Mvc;
  12. namespace YLShipBuildLandMap.Web.Controllers.SystemSetting
  13. {
  14. [Route("api/systemsetting/[controller]/[action]")]
  15. [ApiController]
  16. public class UploadController : ControllerBase
  17. {
  18. [HttpPost]
  19. public async Task<string> Post(IFormFile imgFile, string dir)
  20. {
  21. string[] fileExts;
  22. string fileDescription;
  23. try
  24. {
  25. switch (dir)
  26. {
  27. case "image":
  28. fileExts = new string[] { ".jpg", ".jpeg", ".png", ".bmp", ".gif" };
  29. fileDescription = "图片文件";
  30. break;
  31. case "flash":
  32. fileExts = new string[] { ".swf" };
  33. fileDescription = "flash文件";
  34. break;
  35. case "media":
  36. fileExts = new string[] { ".wmv", ".avi", ".mp4", ".mp3" };
  37. fileDescription = "媒体文件";
  38. break;
  39. case "file":
  40. fileExts = new string[] { ".rar", ".doc", ".docx", ".xls", ".xlsx", ".zip", ".pdf", ".txt" };
  41. fileDescription = "文档";
  42. break;
  43. default:
  44. throw new Exception("不支持的上传文件类型。");
  45. }
  46. var ext = Path.GetExtension(imgFile.FileName);
  47. if (!fileExts.Contains(ext))
  48. {
  49. return new { error = 1, message = "只允许上传" + fileDescription + ",文件扩展名需要以" + string.Join("、", fileExts) + "结尾。" }.ToJson();
  50. }
  51. string url = await FileHelper.Upload(imgFile);
  52. return new { error = 0, url }.ToJson();
  53. }
  54. catch (Exception ex)
  55. {
  56. return new { error = 1, message = ex.Message }.ToJson();
  57. }
  58. }
  59. }
  60. }