我们需要将多个文件打包成Zip格式并下载。您能否建议一种无需使用任何第三方库即可在ASP.NET Core中执行此操作的方法。
在ASP.NET MVC中,我们可以使用https://msdn.microsoft.com/en-us/library/system.io.packaging.aspx来实现。在ASP.NET core 2.0中是否可能?
答案 0 :(得分:0)
我认为这对您有很大帮助
protected FileStreamResult DownloadFolder(string path, string[] names, int count)
{
FileStreamResult fileStreamResult;
var tempPath = Path.Combine(Path.GetTempPath(), "temp.zip");
if (names.Length == 1)
{
path = path.Remove(path.Length - 1);
ZipFile.CreateFromDirectory(path, tempPath, CompressionLevel.Fastest, true);
FileStream fileStreamInput = new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.Delete);
fileStreamResult = new FileStreamResult(fileStreamInput, "APPLICATION/octet-stream");
fileStreamResult.FileDownloadName = names[0] + ".zip";
}
else
{
string extension;
string currentDirectory;
ZipArchiveEntry zipEntry;
ZipArchive archive;
if (count == 0)
{
string directory = Path.GetDirectoryName(path);
string rootFolder = Path.GetDirectoryName(directory);
using (archive = ZipFile.Open(tempPath, ZipArchiveMode.Update))
{
for (var i = 0; i < names.Length; i++)
{
currentDirectory = Path.Combine(rootFolder, names[i]);
foreach (var filePath in Directory.GetFiles(currentDirectory, "*.*", SearchOption.AllDirectories))
{
zipEntry = archive.CreateEntryFromFile(this.contentRootPath + "\\" + filePath, names[i] + filePath.Substring(currentDirectory.Length), CompressionLevel.Fastest);
}
}
}
}
else
{
string lastSelected = names[names.Length - 1];
string selectedExtension = Path.GetExtension(lastSelected);
if (selectedExtension == "")
{
path = Path.GetDirectoryName(Path.GetDirectoryName(path));
path = path.Replace("\\", "/") + "/";
}
using (archive = ZipFile.Open(tempPath, ZipArchiveMode.Update))
{
for (var i = 0; i < names.Length; i++)
{
extension = Path.GetExtension(names[i]);
currentDirectory = Path.Combine(path, names[i]);
if (extension == "")
{
foreach (var filePath in Directory.GetFiles(currentDirectory, "*.*", SearchOption.AllDirectories))
{
zipEntry = archive.CreateEntryFromFile(this.contentRootPath + "\\" + filePath, filePath.Substring(path.Length), CompressionLevel.Fastest);
}
}
else
{
zipEntry = archive.CreateEntryFromFile(this.contentRootPath + "\\" + currentDirectory, names[i], CompressionLevel.Fastest);
}
}
}
}
FileStream fileStreamInput = new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.Delete);
fileStreamResult = new FileStreamResult(fileStreamInput, "APPLICATION/octet-stream");
fileStreamResult.FileDownloadName = "folders.zip";
}
if (File.Exists(tempPath))
{
File.Delete(tempPath);
}
return fileStreamResult;
}