UploadController.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using FileStorage.Enums;
  2. using FileStorage.Models;
  3. using Microsoft.AspNetCore.Hosting;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.AspNetCore.Mvc;
  6. using System;
  7. using System.ComponentModel.DataAnnotations;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Threading.Tasks;
  11. using Volo.Abp.AspNetCore.Mvc;
  12. namespace FileStorage.Controllers
  13. {
  14. public class UploadController : AbpController
  15. {
  16. private readonly IWebHostEnvironment _hostEnvironment;
  17. private readonly FileManager _fileManager;
  18. string[] pictureFormatArray = { ".png", ".jpg", ".jpeg", ".gif", ".PNG", ".JPG", ".JPEG", ".GIF" };
  19. public UploadController(
  20. IWebHostEnvironment hostEnvironment,
  21. FileManager fileManager)
  22. {
  23. _hostEnvironment = hostEnvironment;
  24. _fileManager = fileManager;
  25. }
  26. [HttpPost]
  27. [Route("upload")]
  28. public async Task<ActionResult> Upload([Required]string name, IFormFile file)
  29. {
  30. string uniqueFileName = null;
  31. if (file != null)
  32. {
  33. //限制100M
  34. if (file.Length > 104857600)
  35. {
  36. return new BadRequestObjectResult("上传文件过大");
  37. }
  38. //文件格式
  39. var fileExtension = Path.GetExtension(file.FileName);
  40. if (!pictureFormatArray.Contains(fileExtension))
  41. {
  42. return new BadRequestObjectResult("上传文件格式错误");
  43. }
  44. var size = "";
  45. if (file.Length < 1024)
  46. size = file.Length.ToString() + "B";
  47. else if (file.Length >= 1024 && file.Length < 1048576)
  48. size = ((float)file.Length / 1024).ToString("F2") + "KB";
  49. else if (file.Length >= 1048576 && file.Length < 104857600)
  50. size = ((float)file.Length / 1024 / 1024).ToString("F2") + "MB";
  51. else size = file.Length.ToString() + "B";
  52. string uploadsFolder = Path.Combine(_hostEnvironment.WebRootPath, "Images");
  53. if (!Directory.Exists(uploadsFolder))
  54. {
  55. Directory.CreateDirectory(uploadsFolder);
  56. }
  57. uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
  58. string filePath = Path.Combine(uploadsFolder, uniqueFileName);
  59. using (var fileStream = new FileStream(filePath, FileMode.Create))
  60. {
  61. file.CopyTo(fileStream);
  62. fileStream.Flush();
  63. }
  64. //TODO:文件md5哈希校验
  65. await _fileManager.Create(name, uniqueFileName, fileExtension, "", size, filePath, "/Images/" + uniqueFileName, FileType.Image);
  66. }
  67. return Ok(uniqueFileName);
  68. }
  69. }
  70. }