在 ASP.NET Core 中,您可以使用 System.IO.Compression 命名空间中的 ZipArchive 类来创建一个 zip 文件,然后将多个文件添加到该 zip 文件中,最后将该 zip 文件提供给用户进行下载。

以下是一个示例代码,演示如何将多个文件打包为 zip 并提供下载:

using System.IO;
using System.IO.Compression;
using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
    public IActionResult DownloadFiles()
    {
        // 要打包的文件路径
        string[] filePaths = {
            "path/to/file1.txt",
            "path/to/file2.txt",
            "path/to/file3.txt"
        };

        // 创建一个临时 zip 文件
        var tempZipFile = Path.GetTempFileName();

        // 将文件打包到 zip 文件中
        using (var archive = ZipFile.Open(tempZipFile, ZipArchiveMode.Create))
        {
            foreach (var filePath in filePaths)
            {
                var entryName = Path.GetFileName(filePath);
                archive.CreateEntryFromFile(filePath, entryName);
            }
        }

        // 将 zip 文件提供给用户进行下载
        var fileStream = new FileStream(tempZipFile, FileMode.Open, FileAccess.Read, FileShare.Read);
        return File(fileStream, "application/zip", "download.zip");
    }
}

在上述示例中,您可以将 filePaths 数组中的文件路径替换为您要打包的实际文件路径。然后,将会创建一个临时的 zip 文件,并将文件打包到该 zip 文件中。最后,将该 zip 文件提供给用户进行下载,文件名为 download.zip

请注意,上述示例中的代码将临时 zip 文件存储在服务器的临时目录中。如果您希望将 zip 文件存储在其他位置,可以修改 tempZipFile 变量的赋值语句。

希望以上信息对您有所帮助

net core 将多个文件打包下载

原文地址: https://www.cveoy.top/t/topic/iN5H 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录