AttachFileManager.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 ContractService.BaseInfo;
  14. using ContractService.Configuration;
  15. using IwbZero;
  16. using IwbZero.ToolCommon.LogHelpers;
  17. namespace ContractService.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. if (input.IsUpdate)
  51. {
  52. var entity = await Repository.FirstOrDefaultAsync(a =>
  53. a.TableName == input.TableName && a.ColumnName == input.ColumnName &&
  54. a.SourceKey == input.SourceKey);
  55. if (entity == null)
  56. {
  57. entity = ObjectMapper.Map<SysAttachFile>(input);
  58. await Repository.InsertAsync(entity);
  59. }
  60. else
  61. {
  62. entity.FileExt = input.FileExt;
  63. entity.FileName = input.FileName;
  64. entity.FileTitle = input.FileTitle;
  65. entity.FilePath = lcRetVal;
  66. entity.FileType = input.FileType;
  67. await Repository.UpdateAsync(entity);
  68. }
  69. }
  70. else
  71. {
  72. var entity = ObjectMapper.Map<SysAttachFile>(input);
  73. await Repository.InsertAsync(entity);
  74. }
  75. return;
  76. }
  77. var allowExts = string.IsNullOrEmpty(input.AllowExt)
  78. ? await SettingManager.GetSettingValueAsync(IwbSettingNames.UploadFileExt)
  79. : input.AllowExt;
  80. throw new UserFriendlyException(L("FileUploadFileTypeInvalidFormatter", $"{input.FileName}.{input.FileExt}", allowExts));
  81. }
  82. /// <summary>
  83. /// 上传附件
  84. /// </summary>
  85. /// <returns></returns>
  86. [DisableAuditing]
  87. public async Task FileUpload(string fileInfo, string filePath, string fileName, string fileExt)
  88. {
  89. if (await IsValidFileType(fileExt))
  90. {
  91. var lcRetVal = Base64ToFile(fileInfo, $"{fileName}", fileExt, filePath);
  92. if (lcRetVal.StartsWith("error@"))
  93. {
  94. throw new UserFriendlyException(lcRetVal.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries)[1]);
  95. }
  96. return;
  97. }
  98. var allowExts = await SettingManager.GetSettingValueAsync(IwbSettingNames.UploadFileExt);
  99. throw new UserFriendlyException(L("FileUploadFileTypeInvalidFormatter", $"{fileName}.{fileExt}", allowExts));
  100. }
  101. /// <summary>
  102. /// 上传附件
  103. /// </summary>
  104. /// <returns></returns>
  105. [DisableAuditing]
  106. public async Task FileUpload(string fileInfo, string filePath, string fileName, string fileExt, string allowExt)
  107. {
  108. if (await IsValidFileType(fileExt, allowExt, false, string.IsNullOrEmpty(allowExt)))
  109. {
  110. var lcRetVal = Base64ToFile(fileInfo, $"{fileName}", fileExt, filePath);
  111. if (lcRetVal.StartsWith("error@"))
  112. {
  113. throw new UserFriendlyException(lcRetVal.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries)[1]);
  114. }
  115. this.LogInfo("文件保存路径:" + lcRetVal);
  116. return;
  117. }
  118. allowExt = string.IsNullOrEmpty(allowExt) ? await SettingManager.GetSettingValueAsync(IwbSettingNames.UploadFileExt) : allowExt;
  119. throw new UserFriendlyException(L("FileUploadFileTypeInvalidFormatter", $"{fileName}.{fileExt}", allowExt));
  120. }
  121. private async Task<bool> IsValidFileType(AttachFileCreateDto input)
  122. {
  123. return await IsValidFileType(input.FileExt, input.AllowExt, false, string.IsNullOrEmpty(input.AllowExt));
  124. }
  125. private async Task<bool> IsValidFileType(string fileName, string allowExts = null, bool isName = false,
  126. bool checkAll = false)
  127. {
  128. string ext = isName ? GetFileExt(fileName) : fileName;
  129. allowExts = checkAll
  130. ? $"{allowExts ?? ""},{await SettingManager.GetSettingValueAsync(IwbSettingNames.UploadFileExt)}"
  131. : allowExts;
  132. if (string.IsNullOrEmpty(allowExts))
  133. return true;
  134. string[] extList = allowExts.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  135. foreach (var e in extList)
  136. {
  137. if (ext.ToLower() == e.ToLower())
  138. return true;
  139. }
  140. this.LogError("上传的文件非法:" + fileName);
  141. return false;
  142. }
  143. private string GetFileExt(string fileName)
  144. {
  145. string fileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1, fileName.Length - fileName.LastIndexOf(".", StringComparison.Ordinal) - 1);
  146. return fileExt.ToLower();
  147. }
  148. private string Base64ToFile(string base64Str, string fileName, string fileExt, string filePath)
  149. {
  150. string lcRetVal = "error@";
  151. try
  152. {
  153. fileName = $"{fileName}.{fileExt}";
  154. filePath = filePath.StartsWith("/") ? filePath : ("/" + filePath);
  155. filePath = filePath.EndsWith("/") ? filePath : (filePath + "/");
  156. string path = $"{AppDomain.CurrentDomain.BaseDirectory}{filePath}";
  157. if (!Directory.Exists(path))
  158. Directory.CreateDirectory(path);
  159. byte[] bytes = Convert.FromBase64String(base64Str);
  160. using (FileStream fs = new FileStream($"{path}{fileName}", FileMode.Create, FileAccess.Write))
  161. {
  162. fs.Write(bytes, 0, bytes.Length);
  163. fs.Close();
  164. }
  165. lcRetVal = filePath + fileName;
  166. }
  167. catch (Exception e)
  168. {
  169. this.LogError(e);
  170. lcRetVal += "FileUploadException";
  171. }
  172. return lcRetVal;
  173. }
  174. private string L(string name, params object[] args)
  175. {
  176. return LocalizationHelper.GetSource(IwbZeroConsts.LocalizationSourceName).GetString(name, args);
  177. }
  178. }
  179. }