FwLocalFileHandler.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using FileStorage;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.Extensions.Options;
  4. using System.ComponentModel.DataAnnotations;
  5. using static System.Runtime.InteropServices.JavaScript.JSType;
  6. namespace FileHandlers
  7. {
  8. [Display(Name = "local")]
  9. public class FwLocalFileHandler:FwFileHandlerBase
  10. {
  11. private readonly IOptionsSnapshot<FileUploadOptions> _fileUploadOptions;
  12. public FwLocalFileHandler(IOptionsSnapshot<FileUploadOptions> fileUploadOptions)
  13. {
  14. _fileUploadOptions = fileUploadOptions;
  15. }
  16. public override string Upload(string fileName, long length, string extraInfo,Stream fileData)
  17. {
  18. var settings = _fileUploadOptions.Value.Settings.Where(x=> x.Key.ToLower()=="local").Select(x=>x.Value).FirstOrDefault();
  19. string groupDir = "";
  20. if(settings!=null)
  21. {
  22. groupDir = settings.FirstOrDefault().GroupLocation;
  23. }
  24. if (string.IsNullOrEmpty(groupDir))
  25. {
  26. groupDir = "./uploads";
  27. }
  28. string pathHeader = groupDir;
  29. string fulldir = GetFullPath(pathHeader);
  30. if(!Directory.Exists(fulldir))
  31. {
  32. Directory.CreateDirectory(fulldir);
  33. }
  34. var ext = string.Empty;
  35. if(!string.IsNullOrEmpty(fileName))
  36. {
  37. var dotPos = fileName.LastIndexOf('.');
  38. ext = fileName.Substring(dotPos + 1);
  39. }
  40. var filename = $"{Guid.NewGuid().ToString().Replace("-",string.Empty)}.{ext}";
  41. var fullPath = Path.Combine(fulldir, filename);
  42. using (var fileStream = File.Create(fullPath))
  43. {
  44. fileData.CopyTo(fileStream);
  45. }
  46. fileData.Dispose();
  47. return (Path.Combine(pathHeader, filename));
  48. }
  49. private string GetFullPath(string path)
  50. {
  51. string rv = "";
  52. if (path.StartsWith("."))
  53. {
  54. rv = Path.Combine(Directory.GetCurrentDirectory(), path);
  55. }
  56. else
  57. {
  58. rv = path;
  59. }
  60. rv = Path.GetFullPath(rv);
  61. return rv;
  62. }
  63. }
  64. }