如何使用ASP.NET下载多个文件? [英] How to Download Multiple Files using ASP.NET?
问题描述
我正在尝试使用asp.net下载多个文件.我有一个名为DownloadFileButton的按钮和一个名为FilePath的ArrayList(它包含所有文件路径). 因此,当我单击下载"按钮时,仅下载了一个文件(文件路径"列表中的第一个文件).因为Response.End()导致脚本停止处理.当我注释掉Response.End()时,我在Response.ClearHeaders()处得到了异常.
I am trying to Download multiple files using asp.net. I have a Button called DownloadFileButton and a ArrayList called FilePath(It holds all the File paths). So when i click the Download Button only 1 file is downloaded(the first file in the FilePath List). Because Response.End() causes the script to stop processing. when i comment out the Response.End() then i get an exception at Response.ClearHeaders().
如何克服这个问题?
我的代码:
protected void DownloadFileButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < FilePath.Count; i++)
{
string path = FilePath[i];
FileInfo file = new FileInfo(path);
if(file.Exists)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
}
}
}
}
推荐答案
如何克服这个问题?
how to overcome this?
一个词(或两个词),您不会.
In a word (or two), you don't.
HTTP是一个请求/响应系统.任何答复都必须作为对请求的答复.鉴于此,您无法发送单个请求的多个响应.如果没有其他要求,那么就不会有客户端在监听那些响应(因为它已经获得了正在等待的响应).
HTTP is a request/response system. Any response has to come as a reply to a request. Given that, you can't send multiple responses to a single request. If nothing else, there would be no client listening for those responses (because it already got the response it was waiting for).
因此,从本质上讲,您有两个选择:
So essentially you have two options:
- 发出多个请求,每个下载的文件"一个.这将为客户带来多个期望.
- 使用服务器端代码中的某些存档工具(Zip库是非常标准的)将文件合并为单个文件,然后发送那个作为响应.然后,客户端将需要取消存档. (如果客户端是用户,则可以手动执行.自解压可执行文件Zip可以帮助您解决问题.如果客户端是应用程序,则可以在客户端使用同一库提取存档内容并保存.文件.)
- Issue multiple requests, one for each "file" being downloaded. This will create multiple responses for the client to expect.
- Combine the files into a single file using some archiving tool (Zip libraries are pretty standard for this) in the server-side code and send that file as the response. The client would then need to un-archive it. (If the client is a user, they'd do it manually. A self-extracting executable Zip helps with that. If the client is an application, the same library can be used client-side to extract the contents of the archive and save the files.)
一个请求=一个响应.
这篇关于如何使用ASP.NET下载多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!