public ActionResult BatchDownloadFiles(string id, string type)
{
try
{
if (string.IsNullOrWhiteSpace(id)) throw new Exception("请至少选择一项下载");
var ids = id.Split(',');
var expression = "IsDel=False*" + ids?.ToFormatInStr("RelatedId");
// 这里是查询要下载的附件信息
var files = BLLFactory.CreateTestBLL().GetEntitiesByExpression(expression) ?? throw new Exception("暂无数据");
string networkFilePath = Path.Combine("临时文件存放目录", "TempFiles");
using var msZipFile = new MemoryStream();
using ZipArchive archive = new ZipArchive(msZipFile, ZipArchiveMode.Create);
string defaultFilePath = networkFilePath;
string guid = Guid.NewGuid().ToString();
if (files.Count == 1)
{
var model = files[0];
if (System.IO.File.Exists(model.FullPath.Item1))
return PhysicalFile(model.FullPath.Item1, model.FileType == ".flv" ? "flv-application/octet-stream" : "application/octet-stream", model.FileAllName);//发送文件
if (System.IO.File.Exists(model.FullPath.Item2))
return PhysicalFile(model.FullPath.Item2, model.FileType == ".flv" ? "flv-application/octet-stream" : "application/octet-stream", model.FileAllName);//发送文件
throw new Exception("文件不存在");
}
foreach (var f in files)
{
string tempFilePath = Path.Combine(f.PhysicalPath, "TempFiles");
string filePath = f.FullPath.Item2;
if (System.IO.File.Exists(filePath))
{
Directory.CreateDirectory(Path.Combine(tempFilePath, guid));
string newFileName = "放入压缩包里面的文件名";
string copyPath = Path.Combine(tempFilePath, guid, newFileName + f.FileType);
if (System.IO.File.Exists(copyPath))
{
int i = 1;
while (System.IO.File.Exists(copyPath))
copyPath = Path.Combine(tempFilePath, guid, newFileName + "(" + i++.ToString() + ")" + f.FileType);
}
System.IO.File.Copy(filePath, copyPath, true);
}
}
var zipFilePath = Path.Combine(defaultFilePath, guid + ".zip");
if (System.IO.File.Exists(zipFilePath))
{
System.IO.File.Delete(zipFilePath);//删除已存在的压缩文件
}
DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(defaultFilePath, guid));
if (directoryInfo.Exists)
{
ZipUtility.Zip(Path.Combine(defaultFilePath, guid), zipFilePath);
directoryInfo.Delete(true);
}
if (System.IO.File.Exists(zipFilePath))
return PhysicalFile(zipFilePath, "application/octet-stream", $"{DateTime.Now.ToString("yyyyMMddHHmmss")}.zip");//发送文件
throw new ArgumentException("文件不存在");
}
catch (Exception ex)
{
return MsgJson(ex.Message, false);
}
}