使用 ASP.NET Core 创建和下载 zip 文件

对于最近的一个功能,我必须从用 ASP.NET Core 编写的内部网站下载一批文件。在下载文件之前对其进行压缩,结果证明这是一种轻松实现多文件下载的好方法。.NET 提供了所有需要的功能,在本文中,我将向您展示如何实现它。

首先,我将创建一个新的 ASP.NET Core 网站:

dotnet new mvc

我选择了 MVC 模板,但是没有任何与 zip 相关的代码是特定于 MVC 的。

在本例中,我将创建一个能够压缩和下载一些文件的端点。在现实生活中,后端通常需要输入参数才能知道要压缩什么,但为了简单起见,我将省略这部分。

首先声明没有主体的方法:

Route("downloadzip")

public async Task<IActionResult> DownloadTheZipFile()

{

// ...

}

代码尚未编译,因此让我们修复它。首先构建要压缩的文件列表。在下面的代码中,我将硬编码一些路径,但每个文件可能来自客户端、数据库或第三方:

List<string> files = new List<string>

{

"first/file.txt",

"second/file.txt"

};

接下来,我们需要邮政编码:

using (var memoryStream = new MemoryStream())

{

using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))

{

foreach (var file in files)

{

zipArchive.CreateEntryFromFile(file, Path.GetFileName(file));

}

}

}

代码使用ZipArchive.NET 中提供的类来创建 zip 文件。它被包装在 中,MemoryStream因为我们想从方法中返回一个文件流:

memoryStream.Position = 0;

return File(memoryStream, "application/zip", "download.zip");

重置流后,我将其作为File-method 的一部分返回。

整个方法如下:

Route("downloadzip")

public async Task<IActionResult> DownloadTheZipFile()

{

List<string> files = new List<string>

{

"first/file.txt",

"second/file.txt"

};

using (var memoryStream = new MemoryStream())

{

using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))

{

foreach (var file in files)

{

zipArchive.CreateEntryFromFile(file, Path.GetFileName(file));

}

}

memoryStream.Position = 0;

return File(memoryStream, "application/zip", "my.zip");

}

}

点击F5并调用/downloadzip端点来见证奇迹的发生。

本文中的示例非常简单,没有考虑任何问题。如果您要处理大型 zip 文件,将 zip 文件写入服务器上的临时文件,然后将文件流式传输到客户端可能会更有效。这可以帮助防止因尝试一次将整个 zip 文件保存在内存中而可能出现的内存问题:

var tempFile = Path.GetTempFileName();

using (var zipFile = System.IO.File.Create(tempFile))

using (var zipArchive = new ZipArchive(zipFile, ZipArchiveMode.Create))

{

foreach (var file in files)

{

zipArchive.CreateEntryFromFile(file, Path.GetFileName(file));

}

}

var stream = new FileStream(tempFile, FileMode.Open);

return File(stream, "application/zip", "my.zip");

另外,请记住,压缩和下载大文件可能需要一些时间。在客户端上实现某种进度可以避免用户尝试多次下载 zip 文件,从而占用额外的服务器资源。

就是这样。使用内置类,在 .NET 中压缩文件很容易。公平地说,也有一些不错的外部 NuGet 包可用。比如SharpZipLib(我过去曾使用过)和DotNetZip。

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
韩立学长2 小时前
基于Springboot流浪动物领养网站0kh2iyb4(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
Moment2 小时前
从美团全栈化看 AI 冲击:前端转全栈,是自救还是必然 🤔🤔🤔
前端·后端·面试
a努力。4 小时前
腾讯Java面试被问:String、StringBuffer、StringBuilder区别
java·开发语言·后端·面试·职场和发展·架构
源码获取_wx:Fegn08954 小时前
基于springboot + vue心理健康管理系统
vue.js·spring boot·后端
优弧4 小时前
离开舒适区100天,我后悔了吗?
前端·后端·面试
QD_IT伟5 小时前
SpringBoot项目整合Tlog 数据链路的规范加强
java·spring boot·后端
源码获取_wx:Fegn08955 小时前
基于springboot + vue二手交易管理系统
java·vue.js·spring boot·后端·spring·课程设计
爬山算法5 小时前
Springboot请求和响应相关注解及使用场景
java·spring boot·后端
请为小H留灯5 小时前
Java实际开发@常用注解(附实战场景)
java·后端·个人开发
老华带你飞5 小时前
在线教育|基于springboot + vue在线教育系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端