[英]How to Download Multiple Files using ASP.NET?
I am trying to Download multiple files using asp.net. 我正在尝试使用asp.net下载多个文件。 I have a Button called DownloadFileButton and a ArrayList called FilePath(It holds all the File paths).
我有一个名为DownloadFileButton的按钮和一个名为FilePath的ArrayList(它包含所有文件路径)。 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.
因为Response.End()导致脚本停止处理。 when i comment out the Response.End() then i get an exception at Response.ClearHeaders().
当我注释掉Response.End()时,我在Response.ClearHeaders()处得到了异常。
how to overcome this? 如何克服呢?
My Code: 我的代码:
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 is a request/response system. HTTP是一个请求/响应系统。 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: 因此,基本上您有两种选择:
One request = one response. 一个请求=一个响应。
You can create two or more buttons with asp.net functions to trigger after. 您可以使用asp.net函数创建两个或多个按钮,然后再触发。 For example:
例如:
a href="javascript:myFunction1()">Call function /a> asp:Button ID="myButton1" runat="server" Text="Button1" OnClick="myButton1_Click" /> asp:Button ID="myButton2" runat="server" Text="Button2" OnClick="myButton2_Click" /> asp:Button ID="myButton3" runat="server" Text="Button2" OnClick="myButton3_Click" />
To download multiple files you need "a new response", you can do that using $.ajax with jQuery, for example: 要下载多个文件,您需要“一个新的响应”,您可以使用带有jQuery的$ .ajax,例如:
function myFunction1() { $.ajax({ url: "myPage.aspx", context: document.body }).done(function () { $("#myButton1").trigger("click"); myFunction2().delay(500000); //delay is necessary }); } function myFunction2() { $.ajax({ url: "myPage.aspx", context: document.body }).done(function () { $("#myButton2").trigger("click"); myFunction3().delay(1000000); }); } function myFunction3() { $.ajax({ url: "myPage.aspx", context: document.body }).done(function () { $("#myButton3").trigger("click"); }); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.