FileHelper.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Bowin.Common.Utility;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.Extensions.Configuration;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace Bowin.Common.Files
  10. {
  11. public static class FileHelper
  12. {
  13. private static FileSettings Settings { get; set; }
  14. static FileHelper()
  15. {
  16. var configuration = new ConfigurationBuilder()
  17. .SetBasePath(Directory.GetCurrentDirectory())
  18. .AddJsonFile("appsettings.json")
  19. .Build();
  20. Settings = configuration.GetSection("FileSettings").Get<FileSettings>();
  21. }
  22. public async static Task<string> Upload(IFormFile formFile)
  23. {
  24. string directory = Settings.FilePath + "/" + DateTime.Now.ToString("yyyyMM");
  25. string filePath = directory + "/" + Guid.NewGuid() + Path.GetExtension(formFile.FileName);
  26. if (!Directory.Exists(HttpHelper.MapPath(directory)))
  27. {
  28. Directory.CreateDirectory(HttpHelper.MapPath(directory));
  29. }
  30. using (var stream = System.IO.File.Create(HttpHelper.MapPath(filePath)))
  31. {
  32. await formFile.CopyToAsync(stream);
  33. }
  34. return filePath;
  35. }
  36. public static FileStream GetFileStream(string filePath)
  37. {
  38. var stream = System.IO.File.OpenRead(HttpHelper.MapPath(filePath));
  39. return stream;
  40. }
  41. public static MemoryStream GetMemoryStream(string filePath, bool isDelete)
  42. {
  43. string physicalPath = HttpHelper.MapPath(filePath);
  44. var fileStream = System.IO.File.Open(physicalPath, System.IO.FileMode.Open);
  45. var data = new byte[fileStream.Length];
  46. fileStream.Read(data);
  47. fileStream.Close();
  48. var memoryStream = new MemoryStream(data);
  49. if (isDelete)
  50. {
  51. System.IO.File.Delete(physicalPath);
  52. }
  53. return memoryStream;
  54. }
  55. }
  56. public class FileSettings
  57. {
  58. public string FilePath { get; set; }
  59. }
  60. }