Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...