AttachFileManager.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using Abp.Auditing;
  5. using Abp.AutoMapper;
  6. using Abp.Configuration;
  7. using Abp.Dependency;
  8. using Abp.Domain.Repositories;
  9. using Abp.Localization;
  10. using Abp.Localization.Sources;
  11. using Abp.ObjectMapping;
  12. using Abp.UI;
  13. using WeOnlineApp.BaseInfo;
  14. using WeOnlineApp.Configuration;
  15. using IwbZero;
  16. using IwbZero.ToolCommon.LogHelpers;
  17. namespace WeOnlineApp.CommonManager.AttachFiles
  18. {
  19. public class AttachFileManager : IAttachFileManager, ISingletonDependency
  20. {
  21. public AttachFileManager(ISettingManager settingManager, IRepository<SysAttachFile> repository)
  22. {
  23. SettingManager = settingManager;
  24. Repository = repository;
  25. ObjectMapper = SingletonDependency<AutoMapperObjectMapper>.Instance;
  26. // ObjectMapper = resolver.Resolve<AutoMapperObjectMapper>();
  27. }
  28. private ISettingManager SettingManager { get; }
  29. private IRepository<SysAttachFile> Repository { get; }
  30. private IObjectMapper ObjectMapper { get; }
  31. /// <summary>
  32. /// 上传附件
  33. /// </summary>
  34. /// <param name="input"></param>
  35. /// <returns></returns>
  36. [DisableAuditing]
  37. public async Task FileUpload(AttachFileCreateDto input)
  38. {
  39. if (await IsValidFileType(input))
  40. {
  41. string filePath = string.IsNullOrEmpty(input.FilePath)
  42. ? $"{SettingManager.GetSettingValue(IwbSettingNames.DownloadPath)}/{input.TableName}/{input.ColumnName}"
  43. : input.FilePath;
  44. var lcRetVal = Base64ToFile(input.FileInfo, $"{input.FileName}-{DateTime.Now:yyMMddHHmmssfff}", input.FileExt, filePath);
  45. if (lcRetVal.StartsWith("error@"))
  46. {
  47. throw new UserFriendlyException(lcRetVal.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries)[1]);
  48. }
  49. input.FilePath = lcRetVal;
  50. var entity = await Repository.FirstOrDefaultAsync(a =>
  51. a.TableName == input.TableName && a.ColumnName == input.ColumnName &&
  52. a.SourceKey == input.SourceKey);
  53. if (entity == null)
  54. {
  55. entity = ObjectMapper.Map<SysAttachFile>(input);
  56. await Repository.InsertAsync(entity);
  57. }
  58. else
  59. {
  60. entity.FileExt = input.FileExt;
  61. entity.FileName = input.FileName;
  62. entity.FileTitle = input.FileTitle;
  63. entity.FilePath = lcRetVal;
  64. entity.FileType = input.FileType;
  65. await Repository.UpdateAsync(entity);
  66. }
  67. return;
  68. }
  69. var allowExts = string.IsNullOrEmpty(input.AllowExt)
  70. ? await SettingManager.GetSettingValueAsync(IwbSettingNames.UploadFileExt)
  71. : input.AllowExt;
  72. throw new UserFriendlyException(string.Format(L("FileUploadFileTypeInvalidFormatter"), $"{input.FileName}.{input.FileExt}", allowExts));
  73. }
  74. /// <summary>
  75. /// 上传附件
  76. /// </summary>
  77. /// <returns></returns>
  78. [DisableAuditing]
  79. public async Task FileUpload(string fileInfo, string filePath, string fileName, string fileExt)
  80. {
  81. if (await IsValidFileType(fileExt))
  82. {
  83. var lcRetVal = Base64ToFile(fileInfo, $"{fileName}", fileExt, filePath);
  84. if (lcRetVal.StartsWith("error@"))
  85. {
  86. throw new UserFriendlyException(lcRetVal.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries)[1]);
  87. }
  88. return;
  89. }
  90. var allowExts = await SettingManager.GetSettingValueAsync(IwbSettingNames.UploadFileExt);
  91. throw new UserFriendlyException(string.Format(L("FileUploadFileTypeInvalidFormatter"), $"{fileName}.{fileExt}", allowExts));
  92. }
  93. private async Task<bool> IsValidFileType(AttachFileCreateDto input)
  94. {
  95. return await IsValidFileType(input.FileExt, input.AllowExt, false, string.IsNullOrEmpty(input.AllowExt));
  96. }
  97. private async Task<bool> IsValidFileType(string fileName, string allowExts = null, bool isName = false,
  98. bool checkAll = false)
  99. {
  100. string ext = isName ? GetFileExt(fileName) : fileName;
  101. allowExts = checkAll
  102. ? $"{allowExts ?? ""},{await SettingManager.GetSettingValueAsync(IwbSettingNames.UploadFileExt)}"
  103. : allowExts;
  104. if (string.IsNullOrEmpty(allowExts))
  105. return true;
  106. string[] extList = allowExts.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  107. foreach (var e in extList)
  108. {
  109. if (ext.ToLower() == e.ToLower())
  110. return true;
  111. }
  112. this.LogError("上传的文件非法:" + fileName);
  113. return false;
  114. }
  115. private string GetFileExt(string fileName)
  116. {
  117. string fileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1, fileName.Length - fileName.LastIndexOf(".", StringComparison.Ordinal) - 1);
  118. return fileExt.ToLower();
  119. }
  120. private string Base64ToFile(string base64Str, string fileName, string fileExt, string filePath)
  121. {
  122. string lcRetVal = "error@";
  123. try
  124. {
  125. fileName = $"{fileName}.{fileExt}";
  126. filePath = filePath.StartsWith("/") ? filePath : ("/" + filePath);
  127. filePath = filePath.EndsWith("/") ? filePath : (filePath + "/");
  128. string path = $"{AppDomain.CurrentDomain.BaseDirectory}{filePath}";
  129. if (!Directory.Exists(path))
  130. Directory.CreateDirectory(path);
  131. byte[] bytes = Convert.FromBase64String(base64Str);
  132. using (FileStream fs = new FileStream($"{path}{fileName}", FileMode.Create, FileAccess.Write))
  133. {
  134. fs.Write(bytes, 0, bytes.Length);
  135. fs.Close();
  136. }
  137. lcRetVal = filePath + fileName;
  138. }
  139. catch (Exception e)
  140. {
  141. this.LogError(e);
  142. lcRetVal += "FileUploadException";
  143. }
  144. return lcRetVal;
  145. }
  146. private string L(string name, params object[] args)
  147. {
  148. return LocalizationHelper.GetSource(IwbZeroConsts.LocalizationSourceName).GetString(name, args);
  149. }
  150. }
  151. }