UploadService.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using Attribute;
  2. using Common;
  3. using Infrastructure;
  4. namespace Services
  5. {
  6. /// <summary>
  7. /// 上传文件Service业务层处理
  8. /// </summary>
  9. [AppService(ServiceType = typeof(IUploadService), ServiceLifetime = LifeTime.Transient)]
  10. public class UploadService : IUploadService
  11. {
  12. /// <summary>
  13. /// 上传文件
  14. /// </summary>
  15. /// <param name="file">文件流</param>
  16. /// <returns>上传文件到本地</returns>
  17. public string getPicPath(IFormFile file)
  18. {
  19. var option = App.OptionsSetting;
  20. string dir = option.Upload.LocalSavePath + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
  21. string result = "";
  22. try
  23. {
  24. string dir_c = Function.getPath("/" + dir);
  25. if (!System.IO.Directory.Exists(dir_c))
  26. {
  27. System.IO.Directory.CreateDirectory(dir_c);
  28. }
  29. if (file.Length > 0)
  30. {
  31. var fileName = "MT" + Function.MD5_16(Guid.NewGuid().ToString()) + Path.GetExtension(file.FileName);
  32. // if (!string.IsNullOrEmpty(fname))
  33. // {
  34. // fileName = fname + Path.GetExtension(file.FileName);
  35. // }
  36. var filePath = Path.Combine(dir_c, fileName);
  37. using (var stream = new FileStream(filePath, FileMode.Create))
  38. {
  39. file.CopyTo(stream);
  40. result = "/" + dir + fileName;
  41. stream.Dispose();
  42. stream.Close();
  43. }
  44. }
  45. }
  46. catch (Exception ex)
  47. {
  48. Utils.WriteLog(DateTime.Now.ToString() + ex.ToString(), "上传文件异常");
  49. result = "";
  50. }
  51. return result;
  52. }
  53. }
  54. }