/// <summary>
/// Zip压缩帮助类
/// </summary>
public class ZipHelper
{
/// <summary>
/// 多个上传文件
/// </summary>
/// <param name="mm"></param>
/// <returns></returns>
public static UploadModel UploadFiles(UploadRequestModel mm)
{
string filePath = "";
//上传附件先不删除之前的文件
//DeleteDirAllFile(Directory.GetCurrentDirectory() + $"/UploadFile/{mm.id}/{DateTime.Now.Year}/");
//DeleteDirAllFile(Directory.GetCurrentDirectory() + $"/UploadFile/{mm.id}/");
var currentDate = DateTime.Now;
List<string> result = new List<string>();
var webRootPath = Directory.GetCurrentDirectory();//获取项目路径
if (mm.flag == (int)UpLoadType.报送表)
{
//filePath = $"/UploadFile/{mm.guid}/report/{DateTime.Now.Year}/";
filePath = $"/UploadFile/{mm.guid}/report/";
}
if (mm.flag == (int)UpLoadType.调查报告表)
{
//filePath = $"/UploadFile/{mm.guid}/investigation/{DateTime.Now.Year}/";
filePath = $"/UploadFile/{mm.guid}/investigation/";
}
//创建每日存储文件夹
if (!Directory.Exists(webRootPath + filePath))
{
Directory.CreateDirectory(webRootPath + filePath);
}
if (mm.files != null && mm.files.Count > 0)
{
foreach (var item in mm.files) //上传选定的文件列表
{
if (item != null)
{
//文件后缀
var fileExtension = Path.GetExtension(item.FileName);//获取文件格式,拓展名
//var saveName = item.FileName;
//上传文件按照时间戳重新命名
var name = item.FileName.Substring(0, item.FileName.LastIndexOf('.'));
var saveName = name + "_" + currentDate.ToString("yyyyMMddHHmmss") + fileExtension;
var fileSize = item.Length;
//判断文件大小
if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
{
return new UploadModel { isSuccess = false, msg = $"上传失败,文件【{saveName}】大小超过范围" };
}
//文件保存
using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
{
item.CopyTo(fs);
fs.Flush();
}
//完整的文件路径
var completeFilePath = Path.Combine(filePath, saveName);
result.Add(completeFilePath);
}
}
}
else
{
return new UploadModel { isSuccess = false, msg = "上传失败,未检测上传的文件信息~" };
}
return new UploadModel { isSuccess = true, msg = "上传成功", completeFilePath = result };
}
#region 1.压缩该文件夹下的所有文件
/// <summary>
/// 压缩文件夹(压缩该文件夹下的所有文件)
/// </summary>
/// <param name="dirToZip"></param>
/// <param name="zipedFileName"></param>
/// <param name="compressionLevel">压缩率0(无压缩)9(压缩率最高)</param>
public static Tuple<bool,string> ZipDir(string dirToZip, string zipedFileName, int compressionLevel = 5)
{
try
{
if (Path.GetExtension(zipedFileName) != ".zip")
{
zipedFileName = zipedFileName + ".zip";
}
Hashtable fileList = GetAllFies(dirToZip);
if (fileList == null)
{
return new Tuple<bool, string>(false, "目录不存在或者已删除");
}
if (fileList != null && fileList.Count > 0)
{
using (var zipoutputstream = new ZipOutputStream(System.IO.File.Create(zipedFileName)))
{
zipoutputstream.SetLevel(compressionLevel);
Crc32 crc = new Crc32();
//fileList = GetAllFies(dirToZip);
foreach (DictionaryEntry item in fileList)
{
FileStream fs = new FileStream(item.Key.ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
// ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(dirToZip.Length + 1));
ZipEntry entry = new ZipEntry(Path.GetFileName(item.Key.ToString()))
{
DateTime = (DateTime)item.Value,
Size = fs.Length
};
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipoutputstream.PutNextEntry(entry);
zipoutputstream.Write(buffer, 0, buffer.Length);
}
}
}
return new Tuple<bool, string>(true,"压缩成功");
}
catch (Exception ex)
{
return new Tuple<bool, string>(false, $"压缩失败:{ex.Message}");
}
}
#endregion
#region 2.压缩文件夹或者文件
/// <summary>
/// 压缩多个目录或文件
/// </summary>
/// <param name="folderOrFileList">待压缩的文件夹或者文件,全路径格式,是一个集合</param>
/// <param name="zipedFile">压缩后的文件名,全路径格式</param>
/// <param name="level">压缩等级</param>
/// <param name="password">压宿密码</param>
/// <returns></returns>
public static Tuple<bool, string> ZipManyFilesOrDictorys(IEnumerable<string> folderOrFileList, string zipedFile, int level = 6, string password = "")
{
try
{
bool res = true;
using (var s = new ZipOutputStream(File.Create(zipedFile)))
{
s.SetLevel(level);
if (!string.IsNullOrEmpty(password))
{
s.Password = password;
}
foreach (string fileOrDir in folderOrFileList)
{
//是文件夹
if (Directory.Exists(fileOrDir))
{
res = ZipFileDictory(fileOrDir, s, "");
}
else
{
//文件
res = ZipFileWithStream(fileOrDir, s);
}
}
s.Finish();
s.Close();
return new Tuple<bool, string>(res, "压缩成功");
}
}
catch (Exception ex)
{
return new Tuple<bool, string>(false, $"压缩失败:{ex.Message}");
}
}
/// <summary>
/// 递归压缩文件夹方法
/// </summary>
/// <param name="folderToZip"></param>
/// <param name="s"></param>
/// <param name="parentFolderName"></param>
private static bool ZipFileDictory(string folderToZip, ZipOutputStream s, string parentFolderName)
{
bool res = true;
ZipEntry entry = null;
FileStream fs = null;
Crc32 crc = new Crc32();
try
{
//创建当前文件夹
entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")); //加上 “/” 才会当成是文件夹创建
//entry = new ZipEntry(parentFolderName); //加上 “/” 才会当成是文件夹创建
s.PutNextEntry(entry);
s.Flush();
//先压缩文件,再递归压缩文件夹
var filenames = Directory.GetFiles(folderToZip);
foreach (string file in filenames)
{
//打开压缩文件
fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
}
catch(Exception ex)
{
res = true;
}
finally
{
if (fs != null)
{
fs.Close();
}
if (entry != null)
{
}
GC.Collect();
GC.Collect(1);
}
var folders = Directory.GetDirectories(folderToZip);
foreach (string folder in folders)
{
if (!ZipFileDictory(folder, s, Path.Combine(parentFolderName, Path.GetFileName(folderToZip))))
{
return false;
}
}
return res;
}
/// <summary>
/// 带压缩流压缩单个文件
/// </summary>
/// <param name="fileToZip">要进行压缩的文件名</param>
/// <param name="zipStream"></param>
/// <returns></returns>
private static bool ZipFileWithStream(string fileToZip, ZipOutputStream zipStream)
{
//如果文件没有找到,则报错
if (!File.Exists(fileToZip))
{
throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
}
//FileStream fs = null;
FileStream zipFile = null;
ZipEntry zipEntry = null;
bool res = true;
try
{
zipFile = File.OpenRead(fileToZip);
byte[] buffer = new byte[zipFile.Length];
zipFile.Read(buffer, 0, buffer.Length);
zipFile.Close();
zipEntry = new ZipEntry(Path.GetFileName(fileToZip));
zipStream.PutNextEntry(zipEntry);
zipStream.Write(buffer, 0, buffer.Length);
}
catch
{
res = false;
}
finally
{
if (zipEntry != null)
{
}
if (zipFile != null)
{
zipFile.Close();
}
GC.Collect();
GC.Collect(1);
}
return res;
}
#endregion
/// <summary>
/// 删除文件夹下的所有文件
/// </summary>
/// <param name="dirRoot"></param>
public static void DeleteDirAllFile(string dirRoot)
{
DirectoryInfo aDirectoryInfo = new DirectoryInfo(Path.GetDirectoryName(dirRoot));
if (aDirectoryInfo.Exists)
{
FileInfo[] files = aDirectoryInfo.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo f in files)
{
System.IO.File.Delete(f.FullName);
}
}
}
/// <summary>
/// 获取所有文件
/// </summary>
/// <returns></returns>
private static Hashtable GetAllFies(string dir)
{
Hashtable filesList = new Hashtable();
DirectoryInfo fileDire = new DirectoryInfo(dir);
if (!fileDire.Exists)
{
return null;
}
GetAllDirFiles(fileDire, filesList);
GetAllDirsFiles(fileDire.GetDirectories(), filesList);
return filesList;
}
/// <summary>
/// 获取一个文件夹下的文件
/// </summary>
/// <param name="dir">目录名称</param>
/// <param name="filesList">文件列表HastTable</param>
public static void GetAllDirFiles(DirectoryInfo dir, Hashtable filesList)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
}
/// <summary>
/// 获取一个文件夹下的所有文件夹里的文件
/// </summary>
/// <param name="dirs"></param>
/// <param name="filesList"></param>
public static void GetAllDirsFiles(IEnumerable<DirectoryInfo> dirs, Hashtable filesList)
{
foreach (DirectoryInfo dir in dirs)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
GetAllDirsFiles(dir.GetDirectories(), filesList);
}
}
}
/// <summary>
/// 上传附件返回model
/// </summary>
public class UploadModel
{
public bool isSuccess { get; set; }
public string msg { get; set; }
public List<string> completeFilePath { get; set; } = new List<string>();
}
/// <summary>
/// 上传附件请求model
/// </summary>
public class UploadRequestModel
{
public List<IFormFile> files { get; set; }
public int id { get; set; }
/// <summary>
/// 操作类型 1报表 2报告表
/// </summary>
public int flag { get; set; }
/// <summary>
/// 绑定批量上传的唯一ID
/// </summary>
public string guid { get; set; }
}
调用
[HttpPost]
[ModuleInfo]
[Description("读取数据")]
public IActionResult UploadFiles([FromForm] UploadRequestModel req)
{
try
{
if (string.IsNullOrWhiteSpace(req.guid))
{
return ReturnJson(false, EERRORINFO.无, "guid不能为空");
}
UploadModel model = ZipHelper.UploadFiles(req);
if (model.isSuccess)
{
//上传成功,数据库修改路径
//_accidentLogic.AddOrUpdateReportAttachments(new AddOrUpdateReportAttachmentsModel()
//{
// Id = req.id,
// AttachmentsPath = string.Join(";", model.completeFilePath),
//});
}
string url = AppSettingsReader.GetValue<string>("AccidentReportingURL") + $"{model.completeFilePath?[0].ToString()}";
List<object> objList = new List<object>();
objList.Add(new
{
result = model.isSuccess,
url = url,
createTime = DateTime.Now,
});
//var obj = new { result = model.isSuccess, url = url };
return ReturnJson(objList, EERRORINFO.无, model.msg);
}
catch (Exception ex)
{
string json = JsonConvert.SerializeObject(req);
return ReturnJson(null, EERRORINFO.无, $"批量上传附件异常,请求接口[UploadFiles],请求参数{json},错误消息:{ex.Message}-----------错误位置:{ex.StackTrace}");
}
}
[HttpPost]
[ModuleInfo]
[Description("读取数据")]
public IActionResult CreateZIPFile(UploadRequestModel req)
{
try
{
if (string.IsNullOrWhiteSpace(req.guid))
{
return ReturnJson(false, EERRORINFO.无, "guid不能为空");
}
//报送表和调查报告表压缩成一个zip
string filePath = Directory.GetCurrentDirectory() + $"/UploadFile/{req.guid}/";
//报送表和调查报告单独压缩
//if (req.flag == (int)UpLoadType.报送表)
//{
// filePath = Directory.GetCurrentDirectory() + $"/UploadFile/{req.guid}/report/";
//}
//if (req.flag == (int)UpLoadType.调查报告表)
//{
// filePath = Directory.GetCurrentDirectory() + $"/UploadFile/{req.guid}/investigation/";
//}
string zipFileName = $"{req.guid}-{DateTime.Now:yyyyMMddHHmmss}.zip";
string destinationPath = filePath + zipFileName;
//压缩文件
var folderOrFileList = new List<string>()
{
Directory.GetCurrentDirectory() + $"/UploadFile/{req.guid}/"
};
Tuple<bool, string> result = ZipHelper.ZipManyFilesOrDictorys(folderOrFileList, destinationPath);
//var obj = new { result = result.Item1 };
//return ReturnJson(obj, EERRORINFO.无, result.Item2);
//压缩失败
if (result.Item1 == false)
{
return ReturnJson(false, EERRORINFO.无, result.Item2);
}
//下载文件
return File(new FileStream(destinationPath, FileMode.Open), "application/octet-stream", zipFileName);
}
catch (Exception ex)
{
string json = JsonConvert.SerializeObject(req);
return ReturnJson(null, EERRORINFO.无, $"压缩文件异常,请求接口[UploadFiles],请求参数{json},错误消息:{ex.Message}-----------错误位置:{ex.StackTrace}");
}
}