AttachFilesController.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. [DisableRequestSizeLimit]
  97. public async Task<ActionResult<AttachFile>> PostFile(
  98. [FromForm] IEnumerable<IFormFile> files)
  99. {
  100. var maxAllowedFiles = 3;
  101. long maxFileSize = 1024 * 1024 * 15;
  102. var filesProcessed = 0;
  103. var resourcePath = new Uri($"{Request.Scheme}://{Request.Host}/");
  104. List<AttachFile> uploadResults = new();
  105. foreach (var file in files)
  106. {
  107. var attachFile = new AttachFile();
  108. string trustedFileNameForFileStorage;
  109. var untrustedFileName = file.FileName;
  110. attachFile.Name = untrustedFileName;
  111. Staff uploadUser = Context.Staffs.Where<Staff>(s => s.Name == User.Identity.Name).FirstOrDefault();
  112. if (uploadUser != null)
  113. {
  114. attachFile.UploadUserId = uploadUser.Id;
  115. }
  116. var trustedFileNameForDisplay =
  117. WebUtility.HtmlEncode(untrustedFileName);
  118. if (filesProcessed < maxAllowedFiles)
  119. {
  120. if (file.Length > maxFileSize)
  121. {
  122. logger.LogInformation("{FileName} of {Length} bytes is " +
  123. "larger than the limit of {Limit} bytes (Err: 2)",
  124. trustedFileNameForDisplay, file.Length, maxFileSize);
  125. //uploadResult.ErrorCode = 2;
  126. }
  127. else
  128. {
  129. try
  130. {
  131. trustedFileNameForFileStorage = Path.GetRandomFileName();
  132. var attachfileSavePath = utility.ConfigHelper.GetSectionValue("AttachFileSavePath");
  133. var path = Path.Combine(attachfileSavePath,
  134. trustedFileNameForFileStorage);
  135. await using FileStream fs = new(path, FileMode.Create);
  136. await file.CopyToAsync(fs);
  137. attachFile.SavePath = path;
  138. logger.LogInformation("{FileName} saved at {Path}",
  139. trustedFileNameForDisplay, path);
  140. Context.AttachFiles.Add(attachFile);
  141. Context.SaveChanges();
  142. //uploadResult.Uploaded = true;
  143. //uploadResult.StoredFileName = trustedFileNameForFileStorage;
  144. }
  145. catch (IOException ex)
  146. {
  147. logger.LogError("{FileName} error on upload (Err: 3): {Message}",
  148. trustedFileNameForDisplay, ex.Message);
  149. //uploadResult.ErrorCode = 3;
  150. }
  151. }
  152. filesProcessed++;
  153. }
  154. else
  155. {
  156. logger.LogInformation("{FileName} not uploaded because the " +
  157. "request exceeded the allowed {Count} of files (Err: 4)",
  158. trustedFileNameForDisplay, maxAllowedFiles);
  159. //uploadResult.ErrorCode = 4;
  160. }
  161. uploadResults.Add(attachFile);
  162. }
  163. return new CreatedResult(resourcePath, uploadResults);
  164. }
  165. }
  166. }