public class ZipHelper
{
public static UploadModel UploadFiles(UploadRequestModel mm)
{
string filePath = "";
var currentDate = DateTime.Now;
List<string> result = new List<string>();
var webRootPath = Directory.GetCurrentDirectory();
if (mm.flag == (int)UpLoadType.报送表)
{
filePath = $"/UploadFile/{mm.guid}/report/";
}
if (mm.flag == (int)UpLoadType.调查报告表)
{
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 name = item.FileName.Substring(0, item.FileName.LastIndexOf('.'));
var saveName = name + "_" + currentDate.ToString("yyyyMMddHHmmss") + fileExtension;
var fileSize = item.Length;
if (fileSize > 1024 * 1024 * 10)
{
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.压缩该文件夹下的所有文件
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();
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(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.压缩文件夹或者文件
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}");
}
}
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) + "/"));
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;
}
private static bool ZipFileWithStream(string fileToZip, ZipOutputStream zipStream)
{
if (!File.Exists(fileToZip))
{
throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
}
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
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);
}
}
}
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;
}
public static void GetAllDirFiles(DirectoryInfo dir, Hashtable filesList)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
}
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);
}
}
}
public class UploadModel
{
public bool isSuccess { get; set; }
public string msg { get; set; }
public List<string> completeFilePath { get; set; } = new List<string>();
}
public class UploadRequestModel
{
public List<IFormFile> files { get; set; }
public int id { get; set; }
public int flag { get; set; }
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)
{
}
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,
});
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不能为空");
}
string filePath = Directory.GetCurrentDirectory() + $"/UploadFile/{req.guid}/";
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);
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}");
}
}
|