UploadService.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. OssHelper.Instance.Upload(filePath);
  45. }
  46. }
  47. catch (Exception ex)
  48. {
  49. Utils.WriteLog(DateTime.Now.ToString() + ex.ToString(), "上传文件异常");
  50. result = "";
  51. }
  52. return result;
  53. }
  54. }
  55. }