AttachFilesController.cs 6.7 KB

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