SysFileService.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using Aliyun.OSS.Util;
  7. using OnceMi.AspNetCore.OSS;
  8. namespace Admin.NET.Core.Service;
  9. /// <summary>
  10. /// 系统文件服务 🧩
  11. /// </summary>
  12. [ApiDescriptionSettings(Order = 410, Description = "系统文件")]
  13. public class SysFileService : IDynamicApiController, ITransient
  14. {
  15. private readonly UserManager _userManager;
  16. private readonly SqlSugarRepository<SysFile> _sysFileRep;
  17. private readonly OSSProviderOptions _OSSProviderOptions;
  18. private readonly UploadOptions _uploadOptions;
  19. private readonly IOSSService _OSSService;
  20. private readonly string _imageType = ".jpeg.jpg.png.bmp.gif.tif";
  21. public SysFileService(UserManager userManager,
  22. SqlSugarRepository<SysFile> sysFileRep,
  23. IOptions<OSSProviderOptions> oSSProviderOptions,
  24. IOptions<UploadOptions> uploadOptions,
  25. IOSSServiceFactory ossServiceFactory)
  26. {
  27. _userManager = userManager;
  28. _sysFileRep = sysFileRep;
  29. _OSSProviderOptions = oSSProviderOptions.Value;
  30. _uploadOptions = uploadOptions.Value;
  31. if (_OSSProviderOptions.Enabled)
  32. _OSSService = ossServiceFactory.Create(Enum.GetName(_OSSProviderOptions.Provider));
  33. }
  34. /// <summary>
  35. /// 获取文件分页列表 🔖
  36. /// </summary>
  37. /// <param name="input"></param>
  38. /// <returns></returns>
  39. [DisplayName("获取文件分页列表")]
  40. public async Task<SqlSugarPagedList<SysFile>> Page(PageFileInput input)
  41. {
  42. // 获取所有公开附件
  43. var publicList = _sysFileRep.AsQueryable().ClearFilter().Where(u => u.IsPublic == true);
  44. // 获取私有附件
  45. var privateList = _sysFileRep.AsQueryable().Where(u => u.IsPublic == false);
  46. // 合并公开和私有附件并分页
  47. return await _sysFileRep.Context.UnionAll(publicList, privateList)
  48. .WhereIF(!string.IsNullOrWhiteSpace(input.FileName), u => u.FileName.Contains(input.FileName.Trim()))
  49. .WhereIF(!string.IsNullOrWhiteSpace(input.StartTime.ToString()) && !string.IsNullOrWhiteSpace(input.EndTime.ToString()),
  50. u => u.CreateTime >= input.StartTime && u.CreateTime <= input.EndTime)
  51. .OrderBy(u => u.CreateTime, OrderByType.Desc)
  52. .ToPagedListAsync(input.Page, input.PageSize);
  53. }
  54. /// <summary>
  55. /// 上传文件Base64 🔖
  56. /// </summary>
  57. /// <param name="input"></param>
  58. /// <returns></returns>
  59. [DisplayName("上传文件Base64")]
  60. public async Task<SysFile> UploadFileFromBase64(UploadFileFromBase64Input input)
  61. {
  62. var pattern = @"data:(?<type>.+?);base64,(?<data>[^""]+)";
  63. var regex = new Regex(pattern, RegexOptions.Compiled);
  64. var match = regex.Match(input.FileDataBase64);
  65. byte[] fileData = Convert.FromBase64String(match.Groups["data"].Value);
  66. var contentType = match.Groups["type"].Value;
  67. if (string.IsNullOrEmpty(input.FileName))
  68. input.FileName = $"{YitIdHelper.NextId()}.{contentType.AsSpan(contentType.LastIndexOf('/') + 1)}";
  69. var ms = new MemoryStream();
  70. ms.Write(fileData);
  71. ms.Seek(0, SeekOrigin.Begin);
  72. IFormFile formFile = new FormFile(ms, 0, fileData.Length, "file", input.FileName)
  73. {
  74. Headers = new HeaderDictionary(),
  75. ContentType = contentType
  76. };
  77. var uploadFileInput = input.Adapt<UploadFileInput>();
  78. uploadFileInput.File = formFile;
  79. return await UploadFile(uploadFileInput);
  80. }
  81. /// <summary>
  82. /// 上传多文件 🔖
  83. /// </summary>
  84. /// <param name="files"></param>
  85. /// <returns></returns>
  86. [DisplayName("上传多文件")]
  87. public async Task<List<SysFile>> UploadFiles([Required] List<IFormFile> files)
  88. {
  89. var filelist = new List<SysFile>();
  90. foreach (var file in files)
  91. {
  92. filelist.Add(await UploadFile(new UploadFileInput { File = file }));
  93. }
  94. return filelist;
  95. }
  96. /// <summary>
  97. /// 根据文件Id或Url下载 🔖
  98. /// </summary>
  99. /// <param name="input"></param>
  100. /// <returns></returns>
  101. [DisplayName("根据文件Id或Url下载")]
  102. public async Task<IActionResult> DownloadFile(SysFile input)
  103. {
  104. var file = input.Id > 0 ? await GetFile(input.Id) : await _sysFileRep.CopyNew().GetFirstAsync(u => u.Url == input.Url);
  105. var fileName = HttpUtility.UrlEncode(file.FileName, Encoding.GetEncoding("UTF-8"));
  106. var filePath = Path.Combine(file.FilePath, file.Id.ToString() + file.Suffix);
  107. if (_OSSProviderOptions.Enabled)
  108. {
  109. var stream = await (await _OSSService.PresignedGetObjectAsync(file.BucketName.ToString(), filePath, 5)).GetAsStreamAsync();
  110. return new FileStreamResult(stream.Stream, "application/octet-stream") { FileDownloadName = fileName + file.Suffix };
  111. }
  112. else if (App.Configuration["SSHProvider:Enabled"].ToBoolean())
  113. {
  114. using (SSHHelper helper = new SSHHelper(App.Configuration["SSHProvider:Host"],
  115. App.Configuration["SSHProvider:Port"].ToInt(), App.Configuration["SSHProvider:Username"], App.Configuration["SSHProvider:Password"]))
  116. {
  117. return new FileStreamResult(helper.OpenRead(filePath), "application/octet-stream") { FileDownloadName = fileName + file.Suffix };
  118. }
  119. }
  120. else
  121. {
  122. var path = Path.Combine(App.WebHostEnvironment.WebRootPath, filePath);
  123. return new FileStreamResult(new FileStream(path, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName + file.Suffix };
  124. }
  125. }
  126. /// <summary>
  127. /// 文件预览 🔖
  128. /// </summary>
  129. /// <param name="id"></param>
  130. /// <returns></returns>
  131. [DisplayName("文件预览")]
  132. public async Task<IActionResult> GetPreview([FromRoute] long id)
  133. {
  134. var file = await GetFile(id);
  135. //var fileName = HttpUtility.UrlEncode(file.FileName, Encoding.GetEncoding("UTF-8"));
  136. var filePath = Path.Combine(file.FilePath, file.Id.ToString() + file.Suffix);
  137. if (_OSSProviderOptions.Enabled)
  138. {
  139. var stream = await (await _OSSService.PresignedGetObjectAsync(file.BucketName.ToString(), filePath, 5)).GetAsStreamAsync();
  140. return new FileStreamResult(stream.Stream, "application/octet-stream");
  141. }
  142. else if (App.Configuration["SSHProvider:Enabled"].ToBoolean())
  143. {
  144. using (SSHHelper helper = new SSHHelper(App.Configuration["SSHProvider:Host"],
  145. App.Configuration["SSHProvider:Port"].ToInt(), App.Configuration["SSHProvider:Username"], App.Configuration["SSHProvider:Password"]))
  146. {
  147. return new FileStreamResult(helper.OpenRead(filePath), "application/octet-stream");
  148. }
  149. }
  150. else
  151. {
  152. var path = Path.Combine(App.WebHostEnvironment.WebRootPath, filePath);
  153. return new FileStreamResult(new FileStream(path, FileMode.Open), "application/octet-stream");
  154. }
  155. }
  156. /// <summary>
  157. /// 下载指定文件Base64格式 🔖
  158. /// </summary>
  159. /// <param name="url"></param>
  160. /// <returns></returns>
  161. [DisplayName("下载指定文件Base64格式")]
  162. public async Task<string> DownloadFileBase64([FromBody] string url)
  163. {
  164. if (_OSSProviderOptions.Enabled)
  165. {
  166. using var httpClient = new HttpClient();
  167. HttpResponseMessage response = await httpClient.GetAsync(url);
  168. if (response.IsSuccessStatusCode)
  169. {
  170. // 读取文件内容并将其转换为 Base64 字符串
  171. byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
  172. return Convert.ToBase64String(fileBytes);
  173. }
  174. else
  175. {
  176. throw new HttpRequestException($"Request failed with status code: {response.StatusCode}");
  177. }
  178. }
  179. else if (App.Configuration["SSHProvider:Enabled"].ToBoolean())
  180. {
  181. var sysFile = await _sysFileRep.CopyNew().GetFirstAsync(u => u.Url == url) ?? throw Oops.Oh($"文件不存在");
  182. using (SSHHelper helper = new SSHHelper(App.Configuration["SSHProvider:Host"],
  183. App.Configuration["SSHProvider:Port"].ToInt(), App.Configuration["SSHProvider:Username"], App.Configuration["SSHProvider:Password"]))
  184. {
  185. return Convert.ToBase64String(helper.ReadAllBytes(sysFile.FilePath));
  186. }
  187. }
  188. else
  189. {
  190. var sysFile = await _sysFileRep.CopyNew().GetFirstAsync(u => u.Url == url) ?? throw Oops.Oh($"文件不存在");
  191. var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, sysFile.FilePath);
  192. if (!Directory.Exists(filePath))
  193. Directory.CreateDirectory(filePath);
  194. var realFile = Path.Combine(filePath, $"{sysFile.Id}{sysFile.Suffix}");
  195. if (!File.Exists(realFile))
  196. {
  197. Log.Error($"DownloadFileBase64:文件[{realFile}]不存在");
  198. throw Oops.Oh($"文件[{sysFile.FilePath}]不存在");
  199. }
  200. byte[] fileBytes = File.ReadAllBytes(realFile);
  201. return Convert.ToBase64String(fileBytes);
  202. }
  203. }
  204. /// <summary>
  205. /// 删除文件 🔖
  206. /// </summary>
  207. /// <param name="input"></param>
  208. /// <returns></returns>
  209. [ApiDescriptionSettings(Name = "Delete"), HttpPost]
  210. [DisplayName("删除文件")]
  211. public async Task DeleteFile(DeleteFileInput input)
  212. {
  213. var file = await _sysFileRep.GetByIdAsync(input.Id);
  214. if (file != null)
  215. {
  216. await _sysFileRep.DeleteAsync(file);
  217. if (_OSSProviderOptions.Enabled)
  218. {
  219. await _OSSService.RemoveObjectAsync(file.BucketName.ToString(), string.Concat(file.FilePath, "/", $"{input.Id}{file.Suffix}"));
  220. }
  221. else if (App.Configuration["SSHProvider:Enabled"].ToBoolean())
  222. {
  223. var fullPath = string.Concat(file.FilePath, "/", file.Id + file.Suffix);
  224. using (SSHHelper helper = new SSHHelper(App.Configuration["SSHProvider:Host"],
  225. App.Configuration["SSHProvider:Port"].ToInt(), App.Configuration["SSHProvider:Username"], App.Configuration["SSHProvider:Password"]))
  226. {
  227. helper.DeleteFile(fullPath);
  228. }
  229. }
  230. else
  231. {
  232. var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, file.FilePath, input.Id.ToString() + file.Suffix);
  233. if (File.Exists(filePath))
  234. File.Delete(filePath);
  235. }
  236. }
  237. }
  238. /// <summary>
  239. /// 更新文件 🔖
  240. /// </summary>
  241. /// <param name="input"></param>
  242. /// <returns></returns>
  243. [ApiDescriptionSettings(Name = "Update"), HttpPost]
  244. [DisplayName("更新文件")]
  245. public async Task UpdateFile(SysFile input)
  246. {
  247. var isExist = await _sysFileRep.IsAnyAsync(u => u.Id == input.Id);
  248. if (!isExist) throw Oops.Oh(ErrorCodeEnum.D8000);
  249. await _sysFileRep.UpdateAsync(u => input.Adapt<SysFile>(), u => u.Id == input.Id);
  250. }
  251. /// <summary>
  252. /// 获取文件 🔖
  253. /// </summary>
  254. /// <param name="id"></param>
  255. /// <returns></returns>
  256. [DisplayName("获取文件")]
  257. public async Task<SysFile> GetFile([FromQuery] long id)
  258. {
  259. var file = await _sysFileRep.CopyNew().GetByIdAsync(id);
  260. return file ?? throw Oops.Oh(ErrorCodeEnum.D8000);
  261. }
  262. /// <summary>
  263. /// 上传文件 🔖
  264. /// </summary>
  265. /// <param name="input"></param>
  266. /// <returns></returns>
  267. [DisplayName("上传文件")]
  268. public async Task<SysFile> UploadFile([FromForm] UploadFileInput input)
  269. {
  270. if (input.File == null) throw Oops.Oh(ErrorCodeEnum.D8000);
  271. // 判断是否重复上传的文件
  272. var sizeKb = input.File.Length / 1024; // 大小KB
  273. var fileMd5 = string.Empty;
  274. if (_uploadOptions.EnableMd5)
  275. {
  276. using (var fileStream = input.File.OpenReadStream())
  277. {
  278. fileMd5 = OssUtils.ComputeContentMd5(fileStream, fileStream.Length);
  279. }
  280. // Mysql8 中如果使用了 utf8mb4_general_ci 之外的编码会出错,尽量避免在条件里使用.ToString()
  281. // 因为 Squsugar 并不是把变量转换为字符串来构造SQL语句,而是构造了CAST(123 AS CHAR)这样的语句,这样这个返回值是utf8mb4_general_ci,所以容易出错。
  282. var sysFile = await _sysFileRep.GetFirstAsync(u => u.FileMd5 == fileMd5 && u.SizeKb == sizeKb);
  283. if (sysFile != null) return sysFile;
  284. }
  285. // 验证文件类型
  286. if (!_uploadOptions.ContentType.Contains(input.File.ContentType))
  287. throw Oops.Oh($"{ErrorCodeEnum.D8001}:{input.File.ContentType}");
  288. // 验证文件大小
  289. if (sizeKb > _uploadOptions.MaxSize)
  290. throw Oops.Oh($"{ErrorCodeEnum.D8002},允许最大:{_uploadOptions.MaxSize}KB");
  291. // 获取文件后缀
  292. var suffix = Path.GetExtension(input.File.FileName).ToLower(); // 后缀
  293. if (string.IsNullOrWhiteSpace(suffix))
  294. suffix = string.Concat(".", input.File.ContentType.AsSpan(input.File.ContentType.LastIndexOf('/') + 1));
  295. if (!string.IsNullOrWhiteSpace(suffix))
  296. {
  297. //var contentTypeProvider = FS.GetFileExtensionContentTypeProvider();
  298. //suffix = contentTypeProvider.Mappings.FirstOrDefault(u => u.Value == file.ContentType).Key;
  299. // 修改 image/jpeg 类型返回的 .jpeg、jpe 后缀
  300. if (suffix == ".jpeg" || suffix == ".jpe")
  301. suffix = ".jpg";
  302. }
  303. if (string.IsNullOrWhiteSpace(suffix))
  304. throw Oops.Oh(ErrorCodeEnum.D8003);
  305. // 防止客户端伪造文件类型
  306. if (!string.IsNullOrWhiteSpace(input.AllowSuffix) && !input.AllowSuffix.Contains(suffix))
  307. throw Oops.Oh(ErrorCodeEnum.D8003);
  308. //if (!VerifyFileExtensionName.IsSameType(file.OpenReadStream(), suffix))
  309. // throw Oops.Oh(ErrorCodeEnum.D8001);
  310. // 文件存储位置
  311. var path = string.IsNullOrWhiteSpace(input.SavePath) ? _uploadOptions.Path : input.SavePath;
  312. path = path.ParseToDateTimeForRep();
  313. var newFile = input.Adapt<SysFile>();
  314. newFile.Id = YitIdHelper.NextId();
  315. newFile.BucketName = _OSSProviderOptions.Enabled ? _OSSProviderOptions.Bucket : "Local"; // 阿里云对bucket名称有要求,1.只能包括小写字母,数字,短横线(-)2.必须以小写字母或者数字开头 3.长度必须在3-63字节之间
  316. newFile.FileName = Path.GetFileNameWithoutExtension(input.File.FileName);
  317. newFile.Suffix = suffix;
  318. newFile.SizeKb = sizeKb;
  319. newFile.FilePath = path;
  320. newFile.FileMd5 = fileMd5;
  321. var finalName = newFile.Id + suffix; // 文件最终名称
  322. if (_OSSProviderOptions.Enabled)
  323. {
  324. newFile.Provider = Enum.GetName(_OSSProviderOptions.Provider);
  325. var filePath = string.Concat(path, "/", finalName);
  326. await _OSSService.PutObjectAsync(newFile.BucketName, filePath, input.File.OpenReadStream());
  327. // http://<你的bucket名字>.oss.aliyuncs.com/<你的object名字>
  328. // 生成外链地址 方便前端预览
  329. switch (_OSSProviderOptions.Provider)
  330. {
  331. case OSSProvider.Aliyun:
  332. newFile.Url = $"{(_OSSProviderOptions.IsEnableHttps ? "https" : "http")}://{newFile.BucketName}.{_OSSProviderOptions.Endpoint}/{filePath}";
  333. break;
  334. case OSSProvider.QCloud:
  335. newFile.Url = $"{(_OSSProviderOptions.IsEnableHttps ? "https" : "http")}://{newFile.BucketName}-{_OSSProviderOptions.Endpoint}.cos.{_OSSProviderOptions.Region}.myqcloud.com/{filePath}";
  336. break;
  337. case OSSProvider.Minio:
  338. // 获取Minio文件的下载或者预览地址
  339. // newFile.Url = await GetMinioPreviewFileUrl(newFile.BucketName, filePath);// 这种方法生成的Url是有7天有效期的,不能这样使用
  340. // 需要在MinIO中的Buckets开通对 Anonymous 的readonly权限
  341. var customHost = _OSSProviderOptions.CustomHost;
  342. if (string.IsNullOrWhiteSpace(customHost))
  343. customHost = _OSSProviderOptions.Endpoint;
  344. newFile.Url = $"{(_OSSProviderOptions.IsEnableHttps ? "https" : "http")}://{customHost}/{newFile.BucketName}/{filePath}";
  345. break;
  346. }
  347. }
  348. else if (App.Configuration["SSHProvider:Enabled"].ToBoolean())
  349. {
  350. var fullPath = string.Concat(path.StartsWith('/') ? path : "/" + path, "/", finalName);
  351. using (SSHHelper helper = new SSHHelper(App.Configuration["SSHProvider:Host"],
  352. App.Configuration["SSHProvider:Port"].ToInt(), App.Configuration["SSHProvider:Username"], App.Configuration["SSHProvider:Password"]))
  353. {
  354. helper.UploadFile(input.File.OpenReadStream(), fullPath);
  355. }
  356. }
  357. else
  358. {
  359. newFile.Provider = ""; // 本地存储 Provider 显示为空
  360. var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, path);
  361. if (!Directory.Exists(filePath))
  362. Directory.CreateDirectory(filePath);
  363. var realFile = Path.Combine(filePath, finalName);
  364. using (var stream = File.Create(realFile))
  365. {
  366. await input.File.CopyToAsync(stream);
  367. }
  368. newFile.Url = $"{newFile.FilePath}/{newFile.Id + newFile.Suffix}";
  369. }
  370. await _sysFileRep.AsInsertable(newFile).ExecuteCommandAsync();
  371. return newFile;
  372. }
  373. /// <summary>
  374. /// 上传头像 🔖
  375. /// </summary>
  376. /// <param name="file"></param>
  377. /// <returns></returns>
  378. [DisplayName("上传头像")]
  379. public async Task<SysFile> UploadAvatar([Required] IFormFile file)
  380. {
  381. var sysFile = await UploadFile(new UploadFileInput { File = file, AllowSuffix = _imageType, SavePath = "upload/avatar" });
  382. var sysUserRep = _sysFileRep.ChangeRepository<SqlSugarRepository<SysUser>>();
  383. var user = await sysUserRep.GetByIdAsync(_userManager.UserId);
  384. // 删除已有头像文件
  385. if (!string.IsNullOrWhiteSpace(user.Avatar))
  386. {
  387. var fileId = Path.GetFileNameWithoutExtension(user.Avatar);
  388. await DeleteFile(new DeleteFileInput { Id = long.Parse(fileId) });
  389. }
  390. await sysUserRep.UpdateAsync(u => new SysUser() { Avatar = sysFile.Url }, u => u.Id == user.Id);
  391. return sysFile;
  392. }
  393. /// <summary>
  394. /// 上传电子签名 🔖
  395. /// </summary>
  396. /// <param name="file"></param>
  397. /// <returns></returns>
  398. [DisplayName("上传电子签名")]
  399. public async Task<SysFile> UploadSignature([Required] IFormFile file)
  400. {
  401. var sysFile = await UploadFile(new UploadFileInput { File = file, AllowSuffix = _imageType, SavePath = "upload/signature" });
  402. var sysUserRep = _sysFileRep.ChangeRepository<SqlSugarRepository<SysUser>>();
  403. var user = await sysUserRep.GetByIdAsync(_userManager.UserId);
  404. // 删除已有电子签名文件
  405. if (!string.IsNullOrWhiteSpace(user.Signature) && user.Signature.EndsWith(".png"))
  406. {
  407. var fileId = Path.GetFileNameWithoutExtension(user.Signature);
  408. await DeleteFile(new DeleteFileInput { Id = long.Parse(fileId) });
  409. }
  410. await sysUserRep.UpdateAsync(u => new SysUser() { Signature = sysFile.Url }, u => u.Id == user.Id);
  411. return sysFile;
  412. }
  413. /// <summary>
  414. /// 修改附件关联对象 🔖
  415. /// </summary>
  416. /// <param name="ids"></param>
  417. /// <param name="relationName"></param>
  418. /// <param name="relationId"></param>
  419. /// <param name="belongId"></param>
  420. /// <returns></returns>
  421. [NonAction]
  422. public async Task<int> UpdateRelation(List<long> ids, string relationName, long relationId, long belongId = 0)
  423. {
  424. if (ids == null || ids.Count == 0)
  425. return 0;
  426. return await _sysFileRep.AsUpdateable()
  427. .SetColumns(u => u.RelationName == relationName)
  428. .SetColumns(u => u.RelationId == relationId)
  429. .SetColumns(u => u.BelongId == belongId)
  430. .Where(u => ids.Contains(u.Id))
  431. .ExecuteCommandAsync();
  432. }
  433. /// <summary>
  434. /// 根据关联查询附件
  435. /// </summary>
  436. /// <param name="input"></param>
  437. /// <returns></returns>
  438. /// <exception cref="ArgumentNullException"></exception>
  439. [DisplayName("根据关联查询附件")]
  440. public async Task<List<SysFile>> GetRelationFiles([FromQuery] RelationQueryInput input)
  441. {
  442. return await _sysFileRep.AsQueryable()
  443. .WhereIF(input.RelationId.HasValue && input.RelationId > 0, u => u.RelationId == input.RelationId)
  444. .WhereIF(input.BelongId.HasValue && input.BelongId > 0, u => u.BelongId == input.BelongId.Value)
  445. .WhereIF(!string.IsNullOrWhiteSpace(input.RelationName), u => u.RelationName == input.RelationName)
  446. .WhereIF(!string.IsNullOrWhiteSpace(input.FileTypes), u => input.GetFileTypeBS().Contains(u.FileType))
  447. .Select(u => new SysFile
  448. {
  449. Url = SqlFunc.MergeString("/api/sysFile/Preview/", u.Id.ToString()),
  450. }, true)
  451. .ToListAsync();
  452. }
  453. }