使用 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。

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

相关推荐
就叫飞六吧1 小时前
Spring Security 集成指南:避免 CORS 跨域问题
java·后端·spring
冼紫菜2 小时前
[特殊字符]CentOS 7.6 安装 JDK 11(适配国内服务器环境)
java·linux·服务器·后端·centos
秋野酱4 小时前
Spring Boot 项目的计算机专业论文参考文献
java·spring boot·后端
香饽饽~、4 小时前
【第二篇】 初步解析Spring Boot
java·spring boot·后端
你是狒狒吗4 小时前
消息队列了解一哈
后端
Chandler245 小时前
Go语言 GORM框架 使用指南
开发语言·后端·golang·orm
蚂蚁在飞-6 小时前
Golang基础知识—cond
开发语言·后端·golang
江沉晚呤时8 小时前
.NET Core 中 Swagger 配置详解:常用配置与实战技巧
前端·.netcore
程序员爱钓鱼12 小时前
匿名函数与闭包(Anonymous Functions and Closures)-《Go语言实战指南》原创
后端·golang