ASHX文件下载

时间:2017-05-09 13:49:19

标签: c# asp.net ashx

我正在开发一个项目,用户可以下载存储在MemoryStream中的文件。

我遇到的问题是当用户点击表格中的行来下载特定文件时,下载此文件后页面上的任何后续点击都会导致文件再次下载。

看起来后续请求中的EventTarget仍然是" MyDownloadsPanel"

这是我下载文件的方式

母版页 - PageLoad

if (Request.EventTarget() == "MyDownloadsPanel")
{
    Session["FileExportDownload"] = _fileExportSvc.SelectFileExport(int.Parse(Request.EventArgument()), (string)Session["UsersDatabase"]);
    Response.Redirect("FileExportFileHandler/FileExportDownloadFileHandler.ashx");
}

母版页 - OnItemDataBound

  if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
{
    FileExport fileExport = (FileExport)item.DataItem;

    FileDownloadStatus fileDownloadStatus = GetStatusText(fileExport);
    if (fileDownloadStatus == FileDownloadStatus.Completed)
        item.Attributes["onclick"] = string.Format("__doPostBack('MyDownloadsPanel',{0});", fileExport.ID);

    System.Web.UI.WebControls.Image fileTypeImage = (System.Web.UI.WebControls.Image)item.Cells[0].FindControl("uxFileTypeImage");
    fileTypeImage.ImageUrl = GetDownloadImageFromExtensionPath(fileExport.FileExtension);

    item.Cells[1].Text = ShortenDownloadFilename(fileExport.Filename);

    System.Web.UI.WebControls.Image fileStatusImage = (System.Web.UI.WebControls.Image)item.Cells[2].FindControl("uxFileStatusImage");
    fileStatusImage.ImageUrl = GetImageUrlOnStatus(fileDownloadStatus);
}

FileExportDownloadFileHandler.ashx - ProcessRequest

    FileExport fileExport = (FileExport) HttpContext.Current.Session["FileExportDownload"];
HttpContext.Current.Session["FileExportDownload"] = null;

context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = fileExport.MimeType;
context.Response.AddHeader("content-disposition", "attachment; filename=" + string.Format("{0}_{1}.{2}",fileExport.Filename, fileExport.DateTimeRequested.ToString("dd-MM-yyyy HH:mm"), fileExport.FileExtension));  //this fixes the filename
context.Response.BinaryWrite(fileExport.Data);
context.Response.End();

0 个答案:

没有答案