You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
BookingHeChuan/Myshipping.Application/Helper/FileAttachHelper.cs

306 lines
11 KiB
C#

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
{
/// <summary>
/// 文件附件帮助类
/// </summary>
public static class FileAttachHelper
{
#region 转移文件
/// <summary>
/// 转移文件
/// </summary>
/// <param name="fileDictKey">文件目录KEY</param>
/// <param name="sourceFilePath">源文件完整路径</param>
/// <param name="batchNo">批次号</param>
/// <param name="isLocalTempFile">是否生成本地文件</param>
/// <param name="attachFileType">附件类型 bcfiles-BC文件</param>
/// <returns>返回新的文件路径</returns>
public static async Task<string> MoveFile(string fileDictKey,string sourceFilePath,string batchNo,
bool isLocalTempFile = false,string attachFileType = "bcfiles")
{
var logger = Log.CreateLogger(nameof(FileAttachHelper));
var fileCfg = App.GetOptions<BookingAttachOptions>();
string fileRoot = string.Empty;
if(fileCfg != null)
{
if(!isLocalTempFile)
{
if (!string.IsNullOrWhiteSpace(fileCfg.basePath))
{
fileRoot = fileCfg.basePath;
}
}
else
{
var opt = App.GetOptions<TempFileOptions>().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
{
//删除原文件
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请求文件暂存
/// <summary>
/// 暂存Web请求文件暂存
/// </summary>
/// <param name="fileDictKey">文件目录KEY</param>
/// <param name="file">文件</param>
/// <param name="batchNo">批次号</param>
/// <param name="attachFileType">附件类型 bcfiles-BC文件</param>
/// <returns>返回暂存文件路径</returns>
public static async Task<string> TempSaveWebFile(string fileDictKey, IFormFile file, string batchNo,
string attachFileType = "bcfiles")
{
var logger = Log.CreateLogger(nameof(FileAttachHelper));
var opt = App.GetOptions<TempFileOptions>().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 保存文件并返回文件完整路径
/// <summary>
/// 保存文件并返回文件完整路径
/// </summary>
/// <param name="fileDictKey">文件目录KEY</param>
/// <param name="fileBytes">文件二进制流</param>
/// <param name="batchNo">批次号</param>
/// <param name="fileNameNoSuffix">文件名称不带后缀名</param>
/// <param name="printFileType">文件类型</param>
/// <param name="attachFileType">附件类型 bcfiles-BC文件 sofile-订舱附件</param>
/// <param name="isUseTimeDocName">是否生成日期文件名</param>
/// <returns>返回文件完整路径</returns>
public static async Task<string> 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<BookingAttachOptions>();
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
}
}