AttachFilesController.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.AspNetCore.StaticFiles;
  5. using Microsoft.Extensions.Logging;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Threading.Tasks;
  12. using wispro.sp.entity;
  13. using wispro.sp.share;
  14. namespace wispro.sp.api.Controllers
  15. {
  16. [Route("api/[controller]/[action]")]
  17. [ApiController]
  18. public class AttachFilesController : ControllerBase
  19. {
  20. private readonly IWebHostEnvironment env;
  21. private readonly ILogger<AttachFilesController> logger;
  22. private readonly spDbContext Context;
  23. public AttachFilesController(IWebHostEnvironment env,
  24. ILogger<AttachFilesController> logger,spDbContext context)
  25. {
  26. this.env = env;
  27. this.logger = logger;
  28. this.Context = context;
  29. }
  30. private string GetContentType(string path)
  31. {
  32. var provider = new FileExtensionContentTypeProvider();
  33. string contentType;
  34. if (!provider.TryGetContentType(path, out contentType))
  35. {
  36. contentType = "application/octet-stream";
  37. }
  38. return contentType;
  39. }
  40. [HttpGet,DisableRequestSizeLimit]
  41. public async Task<IActionResult> Download(string Id)
  42. {
  43. var filename = Context.AttachFiles.Where<AttachFile>(a => a.Id == new Guid(Id)).FirstOrDefault();
  44. if (filename != null)
  45. {
  46. var attachfileSavePath = utility.ConfigHelper.GetSectionValue("AttachFileSavePath");
  47. var filePath = Path.Combine(attachfileSavePath,
  48. filename.SavePath);
  49. var context = HttpContext;
  50. if (System.IO.File.Exists(filePath))
  51. {
  52. var memory = new MemoryStream();
  53. await using (var stream = new FileStream(filePath, FileMode.Open))
  54. {
  55. await stream.CopyToAsync(memory);
  56. }
  57. memory.Position = 0;
  58. return File(memory, GetContentType(filename.Name), filename.Name);
  59. }
  60. else
  61. return NotFound();
  62. }
  63. else
  64. {
  65. return NotFound();
  66. }
  67. }
  68. public async Task<bool> Delete(string Id)
  69. {
  70. var filename = Context.AttachFiles.Where<AttachFile>(a => a.Id == new Guid(Id)).FirstOrDefault();
  71. if (filename != null)
  72. {
  73. var attachfileSavePath = utility.ConfigHelper.GetSectionValue("AttachFileSavePath");
  74. var filePath = Path.Combine(attachfileSavePath,
  75. filename.SavePath);
  76. Context.AttachFiles.Remove(filename);
  77. await Context.SaveChangesAsync();
  78. if (System.IO.File.Exists(filePath))
  79. {
  80. System.IO.File.Delete(filePath);
  81. return true;
  82. }
  83. else
  84. {
  85. return false;
  86. }
  87. }
  88. else
  89. {
  90. return false;
  91. }
  92. }
  93. [HttpPost]
  94. public async Task<ActionResult<AttachFile>> PostFile(
  95. [FromForm] IEnumerable<IFormFile> files)
  96. {
  97. var maxAllowedFiles = 3;
  98. long maxFileSize = 1024 * 1024 * 15;
  99. var filesProcessed = 0;
  100. var resourcePath = new Uri($"{Request.Scheme}://{Request.Host}/");
  101. List<AttachFile> uploadResults = new();
  102. foreach (var file in files)
  103. {
  104. var attachFile = new AttachFile();
  105. string trustedFileNameForFileStorage;
  106. var untrustedFileName = file.FileName;
  107. attachFile.Name = untrustedFileName;
  108. Staff uploadUser = Context.Staffs.Where<Staff>(s => s.Name == "何倚雯").FirstOrDefault();
  109. if (uploadUser != null)
  110. {
  111. attachFile.UploadUserId = uploadUser.Id;
  112. }
  113. var trustedFileNameForDisplay =
  114. WebUtility.HtmlEncode(untrustedFileName);
  115. if (filesProcessed < maxAllowedFiles)
  116. {
  117. if (file.Length == 0)
  118. {
  119. logger.LogInformation("{FileName} length is 0 (Err: 1)",
  120. trustedFileNameForDisplay);
  121. //uploadResult.ErrorCode = 1;
  122. }
  123. else if (file.Length > maxFileSize)
  124. {
  125. logger.LogInformation("{FileName} of {Length} bytes is " +
  126. "larger than the limit of {Limit} bytes (Err: 2)",
  127. trustedFileNameForDisplay, file.Length, maxFileSize);
  128. //uploadResult.ErrorCode = 2;
  129. }
  130. else
  131. {
  132. try
  133. {
  134. trustedFileNameForFileStorage = Path.GetRandomFileName();
  135. var attachfileSavePath = utility.ConfigHelper.GetSectionValue("AttachFileSavePath");
  136. var path = Path.Combine(attachfileSavePath,
  137. trustedFileNameForFileStorage);
  138. await using FileStream fs = new(path, FileMode.Create);
  139. await file.CopyToAsync(fs);
  140. attachFile.SavePath = path;
  141. logger.LogInformation("{FileName} saved at {Path}",
  142. trustedFileNameForDisplay, path);
  143. Context.AttachFiles.Add(attachFile);
  144. Context.SaveChanges();
  145. //uploadResult.Uploaded = true;
  146. //uploadResult.StoredFileName = trustedFileNameForFileStorage;
  147. }
  148. catch (IOException ex)
  149. {
  150. logger.LogError("{FileName} error on upload (Err: 3): {Message}",
  151. trustedFileNameForDisplay, ex.Message);
  152. //uploadResult.ErrorCode = 3;
  153. }
  154. }
  155. filesProcessed++;
  156. }
  157. else
  158. {
  159. logger.LogInformation("{FileName} not uploaded because the " +
  160. "request exceeded the allowed {Count} of files (Err: 4)",
  161. trustedFileNameForDisplay, maxAllowedFiles);
  162. //uploadResult.ErrorCode = 4;
  163. }
  164. uploadResults.Add(attachFile);
  165. }
  166. return new CreatedResult(resourcePath, uploadResults);
  167. }
  168. }
  169. }