I’ve created a page that allows users to download a file when they click a button… the button’s onclick event is linked to the following chunk of code:
this.Page.Response.Clear();
this.Page.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Zip;
this.Page.Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + System.IO.Path.GetFileName(filename) + "\"");
this.Page.Response.TransmitFile(filename);
this.Page.Response.Flush();
this.Page.Response.End();
The download works fine, but now when I try to interact with the page, (for instance, hit the download button again), nothing posts back.
Am I responding to the download request incorrectly (should I be using a different/new response object), or is there something else I need to do to make the page active after the download?
Edit:
So I’ve tried encorporating the two posters suggestions for creating a httphandler, and calling a Response.Redirect to the handler from the button’s click event.
void submitButton_Click(object sender, EventArgs e)
{
label.Text = "Boo!";
this.Page.Response.Redirect("~/ViewAttachment.ashx?id=foo", false);
}
If I step through this on the debugger, it continues after the redirect call, but the page just returns to a state where the button doesn’t work, and the labels have their default values. Am I now doing the redirect wrong?
If using another handler an option?
Here’s a slimmed down version of what I’ve used before (suggestions welcome this was a quick write). The HttpHandler (AttachmentFile is just a class with the blob data and some attributes collected when the file was uploaded):
In the
web.config:Then all you do is render a link in the form of
~/ViewAttachment.ashx?ID=5on the page, clicking the button will download the file, but not mess with your page’s lifecycle at all.Now there are more considerations, like security and such….I trimmed them out for this example. I’m also using this style of link:
~/Attachment/{id}via webforms routing…if either of these interest you I’ll update to include them. Or you could hate this approach all-together…just letting you know it’s an option.