ASP.NET: can I force a download of a stored file and update a label in the same event handler?
I've got a ListView datasourced to a database displaying a list of files to be downloaded along with a download count for each. In the ItemTemplate I use a Label to display the current count and a LinkButton with it's Text set to the file name and it's Command set to "select", so as to fire the Listviews SelectedIndexChanging event. All this works fine and I can force the download dialog box to appear but can't get the label updated (which indicates the new download count). I suspect since I'm using the Response to download the binary data, it loses all info to update the label...One thought I have is to save the response stream before I download the file then restore it to it's original state and try to update the ItemTemplates label.
protected void FileListView_SelectedIndexChanging( Object sender, ListViewSelectEventArgs e )
{
ListViewItem item = (ListViewItem)PresetUploadListView.Items[e.NewSelectedIndex];
LinkButton lb = (LinkButton)item.Fi开发者_StackOverflow中文版ndControl( "PresetUploadTitle" );
int fileID = Convert.ToInt32( lb.CommandArgument.ToString( ), 10 );
byte[] fileData = GetFileDataFromDatabasePreset(fileID);
try
{
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + lb.Text + ".zip");
BinaryWriter bw = new BinaryWriter(Response.OutputStream);
bw.Write(fileData);
bw.Close();
Response.ContentType = "application/zip";
Response.Flush();
//Response.Close();
//Response.End();
}
catch (Exception ex)
{
String s = ex.Message + " " + ex.InnerException;
}
Label l = (Label)item.FindControl("PresetUploadDownloads");
int downloadCount = IncandreturnDownloadCount(fileID);
l.Text = downloadCount.ToString(); //+> not getting updated...
e.Cancel = true;
}
Your request can't give two different responses. It can't respond to a page change and serve a file at the same time.
There are a few options available.
Use
window.open
in JavaScript to open a window to the file handler that will initiate the download before the page posts back. The download will begin in a different window, then you update your label in the post back.Update the label first with an AJAX call, then on success of the AJAX call, post back and do your file download.
精彩评论