Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

c# - How to Download Multiple Files using ASP.NET?

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().

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();
            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

how to overcome this?

In a word (or two), you don't.

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:

  1. Issue multiple requests, one for each "file" being downloaded. This will create multiple responses for the client to expect.
  2. 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.)

One request = one response.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...