AttachmentController.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using Cksoft.Unity;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Hosting;
  4. using Microsoft.AspNetCore.Mvc;
  5. using System;
  6. using System.IO;
  7. using System.Threading.Tasks;
  8. namespace DllEapBll.Controllers
  9. {
  10. /// <summary>
  11. /// 附件服务
  12. /// </summary>
  13. [Route("eap/api/[controller]/[action]")]
  14. [Authorize]
  15. [ApiController]
  16. public class AttachmentController : ControllerBase
  17. {
  18. private readonly IHostingEnvironment _hostingEnvironment;
  19. /// <summary>
  20. ///
  21. /// </summary>
  22. /// <param name="hostingEnvironment"></param>
  23. public AttachmentController(IHostingEnvironment hostingEnvironment)
  24. {
  25. _hostingEnvironment = hostingEnvironment;
  26. }
  27. /// <summary>
  28. /// 上传
  29. /// </summary>
  30. /// <returns></returns>
  31. [HttpPost]
  32. public async Task<EapResponse> Upload()
  33. {
  34. var request = Request;
  35. var file = request.Form.Files["file"];
  36. var dateNow = DateTime.Now;
  37. var extension = this.GetFileAExtension(file.FileName);
  38. var fileNewName = Guid.NewGuid().ToString() + "." + extension;
  39. Stream stream = new MemoryStream();
  40. try
  41. {
  42. string path = $"/Upload/{dateNow.Year}/{dateNow.Month}/{dateNow.Day}/";
  43. string phyicPath = _hostingEnvironment.WebRootPath + path;
  44. string savedPath = phyicPath + fileNewName;
  45. this.CreateDirectory(phyicPath);
  46. stream = file.OpenReadStream();
  47. byte[] bs = new byte[stream.Length];
  48. stream.Read(bs, 0, bs.Length);
  49. FileStream fs = new FileStream(savedPath, FileMode.CreateNew);
  50. fs.Write(bs, 0, bs.Length);
  51. await Task.CompletedTask;
  52. return new EapResponse()
  53. {
  54. Code = 1,
  55. Msg = path + fileNewName,
  56. };
  57. }
  58. catch (Exception e)
  59. {
  60. return new EapResponse
  61. {
  62. Code = -1,
  63. Msg = e.Message
  64. };
  65. }
  66. finally
  67. {
  68. stream.Close();
  69. }
  70. }
  71. private void CreateDirectory(string path)
  72. {
  73. if (!Directory.Exists(path))
  74. {
  75. Directory.CreateDirectory(path);
  76. }
  77. }
  78. private string GetFileAExtension(string fileName)
  79. {
  80. var arr = fileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
  81. if (arr == null || arr.Length <= 0)
  82. {
  83. return null;
  84. }
  85. return arr[arr.Length - 1];
  86. }
  87. }
  88. }