using Furion; using Furion.FriendlyException; using Furion.Logging; using Furion.RemoteRequest.Extensions; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Myshipping.Application.ConfigOption; using Myshipping.Application.Entity; using Myshipping.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Myshipping.Application { /// /// 文件附件帮助类 /// public static class FileAttachHelper { #region 转移文件 /// /// 转移文件 /// /// 文件目录KEY /// 源文件完整路径 /// 批次号 /// 是否生成本地文件 /// 附件类型 bcfiles-BC文件 /// 是否保留原文件 /// 返回新的文件路径 public static async Task MoveFile(string fileDictKey,string sourceFilePath,string batchNo, bool isLocalTempFile = false,string attachFileType = "bcfiles",bool isKeepSource = false) { var logger = Log.CreateLogger(nameof(FileAttachHelper)); var fileCfg = App.GetOptions(); string fileRoot = string.Empty; if(fileCfg != null) { if(!isLocalTempFile) { if (!string.IsNullOrWhiteSpace(fileCfg.basePath)) { fileRoot = fileCfg.basePath; } } else { var opt = App.GetOptions().Path; if (!string.IsNullOrWhiteSpace(fileCfg.relativePath)) { fileRoot = $"{Path.Combine(App.WebHostEnvironment.WebRootPath, opt)}"; } } } if (string.IsNullOrWhiteSpace(fileRoot)) fileRoot = App.WebHostEnvironment.WebRootPath; string relativePath = fileCfg.relativePath; if (!string.IsNullOrWhiteSpace(attachFileType)) relativePath += $"\\{attachFileType}"; if (!string.IsNullOrWhiteSpace(fileDictKey)) relativePath += $"\\{fileDictKey}"; relativePath += $"\\{DateTime.Now.ToString("yyyyMMddHHmmss")}"; string filePath = $"{fileRoot}\\{relativePath}"; string fileFullName = $"{filePath}\\{new System.IO.FileInfo(sourceFilePath).Name}"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { relativePath = relativePath.Replace("\\", "/"); filePath = filePath.Replace("\\", "/"); fileFullName = fileFullName.Replace("\\", "/"); } logger.LogInformation("批次={no} 生成文件保存路径完成 路由={filePath} 服务器系统={system}", batchNo, filePath, RuntimeInformation.OSDescription); //预先创建目录 if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } if (sourceFilePath.StartsWith("http", StringComparison.OrdinalIgnoreCase) || sourceFilePath.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { var bcStream = await sourceFilePath.GetAsStreamAsync(); using (var fileStream = File.Create(fileFullName)) { await bcStream.CopyToAsync(fileStream); } } else { System.IO.FileStream file = new System.IO.FileStream(sourceFilePath, FileMode.Open, FileAccess.Read); using (var fileStream = File.Create(fileFullName)) { await file.CopyToAsync(fileStream); } file.Close(); try { if (!isKeepSource) { //删除原文件 System.IO.File.Delete(sourceFilePath); } } catch(Exception delEx) { logger.LogInformation("批次={no} 删除文件异常 filepath={path} ex={ex}", batchNo, fileFullName, delEx.Message); } } logger.LogInformation("批次={no} 完成文件保存 filepath={path}", batchNo, fileFullName); string bookFilePath = string.Empty; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { bookFilePath = System.Text.RegularExpressions.Regex.Match(fileFullName, relativePath.Replace("/", "\\/") + ".*").Value; } else { bookFilePath = System.Text.RegularExpressions.Regex.Match(fileFullName, relativePath.Replace("\\", "\\\\") + ".*").Value; } return bookFilePath; } #endregion #region 暂存Web请求文件暂存 /// /// 暂存Web请求文件暂存 /// /// 文件目录KEY /// 文件 /// 批次号 /// 附件类型 bcfiles-BC文件 /// 返回暂存文件路径 public static async Task TempSaveWebFile(string fileDictKey, IFormFile file, string batchNo, string attachFileType = "bcfiles") { var logger = Log.CreateLogger(nameof(FileAttachHelper)); var opt = App.GetOptions().Path; string filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, opt); if (!string.IsNullOrWhiteSpace(attachFileType)) filePath += $"\\{attachFileType}"; if (!string.IsNullOrWhiteSpace(fileDictKey)) filePath += $"\\{fileDictKey}"; string fileFullName = $"{filePath}\\{file.FileName}"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { filePath = filePath.Replace("\\", "/"); fileFullName = fileFullName.Replace("\\", "/"); } logger.LogInformation("批次={no} 生成文件保存路径完成 路由={filePath} 服务器系统={system}", batchNo, filePath, RuntimeInformation.OSDescription); //预先创建目录 if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } using (var fileStream = File.Create(fileFullName)) { await file.CopyToAsync(fileStream); } return fileFullName; } #endregion #region 保存文件并返回文件完整路径 /// /// 保存文件并返回文件完整路径 /// /// 文件目录KEY /// 文件二进制流 /// 批次号 /// 文件名称不带后缀名 /// 文件类型 /// 附件类型 bcfiles-BC文件 sofile-订舱附件 /// 是否生成日期文件名 /// 返回文件完整路径 public static async Task SaveFile(string fileDictKey, byte[] fileBytes, string batchNo, string fileNameNoSuffix, PrintFileTypeEnum printFileType, string attachFileType = "sofiles", bool isUseTimeDocName = false) { var logger = Log.CreateLogger(nameof(FileAttachHelper)); var fileCfg = App.GetOptions(); string fileRoot = string.Empty; if (fileCfg != null) { if (!string.IsNullOrWhiteSpace(fileCfg.basePath)) { fileRoot = fileCfg.basePath; } } if (string.IsNullOrWhiteSpace(fileRoot)) fileRoot = App.WebHostEnvironment.WebRootPath; string relativePath = fileCfg.relativePath; if (!string.IsNullOrWhiteSpace(attachFileType)) relativePath += $"\\{attachFileType}"; if (!string.IsNullOrWhiteSpace(fileDictKey)) relativePath += $"\\{fileDictKey}"; relativePath += $"\\{DateTime.Now.ToString("yyyyMMddHHmmssfff")}"; string filePath = $"{fileRoot}\\{relativePath}"; var fileType = string.Empty; if (printFileType == PrintFileTypeEnum.PDF) { fileType = ".pdf"; } else if (printFileType == PrintFileTypeEnum.XLSX) { fileType = ".xlsx"; } else if (printFileType == PrintFileTypeEnum.DOCX) { fileType = ".docx"; } else if (printFileType == PrintFileTypeEnum.XLS) { fileType = ".xls"; } else if (printFileType == PrintFileTypeEnum.DOC) { fileType = ".doc"; } string curFileName = fileNameNoSuffix; if (isUseTimeDocName) { curFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff"); } string fileFullName = $"{filePath}\\{curFileName}{fileType}"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { relativePath = relativePath.Replace("\\", "/"); filePath = filePath.Replace("\\", "/"); fileFullName = fileFullName.Replace("\\", "/"); } logger.LogInformation("批次={no} 生成文件保存路径完成 路由={filePath} 服务器系统={system}", batchNo, filePath, RuntimeInformation.OSDescription); //预先创建目录 if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } await File.WriteAllBytesAsync(fileFullName, fileBytes); string bookFilePath = string.Empty; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { bookFilePath = System.Text.RegularExpressions.Regex.Match(fileFullName, relativePath.Replace("/", "\\/") + ".*").Value; } else { bookFilePath = System.Text.RegularExpressions.Regex.Match(fileFullName, relativePath.Replace("\\", "\\\\") + ".*").Value; } return bookFilePath; } #endregion } }