C# 如何向客户端发送多个要下载的文件

C# 如何向客户端发送多个要下载的文件,c#,asp.net,C#,Asp.net,我正在使用处理程序(.ashx)来处理一些文件。我有一个存放电子书的文件夹。我以图书PK命名,每本书可能有几种不同的格式: 211.html 211.pdf 211.prc 以下测试代码成功下载了一本书 context.Response.ContentType = "application/octet-stream"; context.Response.AppendHeader("Content-Disposition", "attachment;filename=myfile.pdf");

我正在使用处理程序(.ashx)来处理一些文件。我有一个存放电子书的文件夹。我以图书PK命名,每本书可能有几种不同的格式:

211.html
211.pdf
211.prc
以下测试代码成功下载了一本书

context.Response.ContentType = "application/octet-stream";
context.Response.AppendHeader("Content-Disposition", "attachment;filename=myfile.pdf");
context.Response.TransmitFile(context.Server.MapPath("~/Media/eBooks/212.pdf"));
我如何为客户提供三种不同的格式?(现有组织的客户端不在文件夹中)

我试着这样做:

DirectoryInfo bookDir  = new DirectoryInfo(context.Server.MapPath("~/Media/eBooks"));
FileInfo[] f  = bookDir.GetFiles();

foreach (var n in f)
{
    context.Response.AppendHeader("Content-Disposition", "attachment;filename=myfile.pdf");
    context.Response.TransmitFile(context.Server.MapPath("~/Media/eBooks/212.pdf"));
}

但是它只下载一个没有文件扩展名的文件。

在一个响应中发送多个文件的唯一方法是将它们放入一个归档包中,例如
.zip
文件。这至少可以通过代码使用各种工具来完成(IIRC现在主.NET框架中有一个zip打包程序;否则,SharpZipLib会很好地完成这项工作)。

要发送多个要下载的文件,您应该使用SharpZipLib或其他文件压缩实用程序来压缩它们,文件应压缩,然后下载链接可以发送到客户端下载他们一次。下面的代码使用ICSharpCode.SharpZipLib.dll库。 您可以调用该类并传递要压缩的文件

public string Makezipfile(string[] files)
    {

  string[] filenames = new string[files.Length];


        for (int i = 0; i < files.Length; i++)
            filenames[i] = HttpContext.Current.Request.PhysicalApplicationPath + files[i].Replace(HttpContext.Current.Request.UrlReferrer.ToString(), "");
    string DirectoryName = filenames[0].Remove(filenames[0].LastIndexOf('/'));
    DirectoryName = DirectoryName.Substring(DirectoryName.LastIndexOf('/') + 1).Replace("\\", "");

    try
    {

        string newFile = HttpContext.Current.Request.PhysicalApplicationPath + "your image directory\\" + DirectoryName + ".zip";
        if (File.Exists(newFile))
            File.Delete(newFile);

        using (ZipFile zip = new ZipFile())
        {

            foreach (string file in filenames)
            {

                string newfileName = file.Replace("\\'", "'");
                zip.CompressionLevel = 0;
                zip.AddFile(newfileName, "");
            }

            zip.Save(newFile);
        }
    }
    catch (Exception ex)
    {
        //Console.WriteLine("Exception during processing {0}", ex);
        Response.Write(ex);
        // No need to rethrow the exception as for our purposes its handled.
    }
    string a;
    a = "your images/" + DirectoryName + ".zip";
    return a; 

}
公共字符串Makezipfile(字符串[]文件)
{
string[]filename=新字符串[files.Length];
for(int i=0;i
我承认这里提到的好的Zip解决方案,但是您是否可以使用javascript/XHR对处理程序进行3次调用,每次请求不同的文件格式

诚然,您受到浏览器支持的并发请求数量的限制,尽管我相信浏览器会将请求排队超过限制


好处是用户不需要处理zip文件,这可能会让他们感到困惑。相反,他们应该获得3个单独的下载。

我同意,但我认为如果他可以为每个zip文件下载创建一个进程ID,那么他可以跟踪每个下载,并且进程将在后台运行。如果用户启动要下载的zip文件,那么用户可以发送一个进程id和要下载的文件,同时如果他启动另一个要下载的zip文件,那么将生成第二个进程id并发送到后台类。当进程在后台完成时,它返回要下载的进程id和zipfiles路径。