文件下载后更新页面

发布于 2024-09-29 03:28:03 字数 1159 浏览 1 评论 0原文

前几天,在堆栈溢出的一些精彩帮助之后,我整理了一个下载脚本。但是我现在发现文件下载后我需要重新加载页面以摆脱 aspx 页面上的进度模板。在我添加下载代码之前,删除模板的代码就起作用了。

删除进度模板的代码: upFinanceMasterScreen.Update();

我尝试在重定向到 IHttpHandler 之前和之后调用此方法,

Response.Redirect("Download.ashx?ReportName=" + "RequestingTPNLeagueTable.pdf");


public class Download : IHttpHandler {

public void ProcessRequest(HttpContext context)
{    

   StringBuilder sbSavePath = new StringBuilder();
   sbSavePath.Append(DateTime.Now.Day);
   sbSavePath.Append("-");
   sbSavePath.Append(DateTime.Now.Month);
   sbSavePath.Append("-");
   sbSavePath.Append(DateTime.Now.Year);

    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.ContentType = "application/pdf";
    HttpResponse objResponce = context.Response;
    String test = HttpContext.Current.Request.QueryString["ReportName"];
    HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=" + test);
    objResponce.WriteFile(context.Server.MapPath(@"Reports\" + sbSavePath + @"\" + test));    

}
 public bool IsReusable { get { return true; } } 

感谢您提供的任何帮助!

I put together a download script after some wonderful help from stack overflow the other day. However I have now found that after the file has been downloaded I need to reload the page to get rid of the progress template on the aspx page. The code to remove the template worked before I added in the download code.

Code to remove progress template: upFinanceMasterScreen.Update();

I've tried calling putting this before and after the redirect to the IHttpHandler

Response.Redirect("Download.ashx?ReportName=" + "RequestingTPNLeagueTable.pdf");


public class Download : IHttpHandler {

public void ProcessRequest(HttpContext context)
{    

   StringBuilder sbSavePath = new StringBuilder();
   sbSavePath.Append(DateTime.Now.Day);
   sbSavePath.Append("-");
   sbSavePath.Append(DateTime.Now.Month);
   sbSavePath.Append("-");
   sbSavePath.Append(DateTime.Now.Year);

    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.ContentType = "application/pdf";
    HttpResponse objResponce = context.Response;
    String test = HttpContext.Current.Request.QueryString["ReportName"];
    HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=" + test);
    objResponce.WriteFile(context.Server.MapPath(@"Reports\" + sbSavePath + @"\" + test));    

}
 public bool IsReusable { get { return true; } } 

Thanks for any help you can provide!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

半枫 2024-10-06 03:28:03

当您发回文件供用户下载时,就是 HTTP 请求。换句话说,您可以进行刷新浏览器页面的回发或者您可以发送文件供用户下载。如果没有特殊的技巧,你就无法同时做到这两点。

这就是为什么大多数网站在您下载文件时,首先会将您带到一个新页面,上面写着“您的下载即将开始”,然后将您“重定向”到要下载的文件使用元刷新或 JavaScript。

例如,当您转到此处下载 .NET 4 运行时时

: displaylang=en&pf=true" rel="noreferrer">http://www.microsoft.com/downloads/en/confirmation.aspx?FamilyID=0a391abd-25c1-4fc0-919f-b21f31ab88b7&displaylang=en&pf= true

它呈现页面,然后使用以下元刷新标记实际为用户提供要下载的文件:

<META HTTP-EQUIV="refresh" content=".1; URL=http://download.microsoft.com/download/9/5/A/95A9616B-7A37-4AF6-BC36-D6EA96C8DAAE/dotNetFx40_Full_x86_x64.exe" />

您可能必须在应用程序中执行类似的操作。但是,如果您确实有兴趣在文件完全下载之后执行某些操作,那么您就不走运了,因为没有任何事件可以将其传达给浏览器。唯一的方法是 AJAX 上传< /a> 就像 gmail 在上传附件时使用的那样。

When you send back a file for the user to download, that is the HTTP request. In other words, you can either have a post-back which refreshes the browser page or you can send a file for the user to download. You cannot do both without special tricks.

This is why most sites when you download a file, it first takes you to a new page that says, "Your download is about to begin", and then subsequently "redirects" you to the file to download using meta-refresh or javascript.

For example, when you go here to download the .NET 4 runtime:

http://www.microsoft.com/downloads/en/confirmation.aspx?FamilyID=0a391abd-25c1-4fc0-919f-b21f31ab88b7&displaylang=en&pf=true

It renders the page, then uses the following meta-refresh tag to actually give the user the file to download:

<META HTTP-EQUIV="refresh" content=".1; URL=http://download.microsoft.com/download/9/5/A/95A9616B-7A37-4AF6-BC36-D6EA96C8DAAE/dotNetFx40_Full_x86_x64.exe" />

You'll probably have to do something similar in your app. However, if you are truly interested in doing something after the file is completely downloaded, you're out of luck, as there's no event to communicate that to the browser. The only way to do that is an AJAX upload like gmail uses when you upload an attachment.

颜漓半夏 2024-10-06 03:28:03

就我而言,我使用的是 MVC,我只是希望页面在选择下载按钮后刷新几秒钟,以显示新的下载计数。我正在从控制器返回文件。

为此,我只需向下载按钮添加一个 onclick 事件来更改视图,该按钮调用以下脚本(也在视图中):

setTimeout(function () {
        window.location.reload(1);
    }, 5000);

它符合我的目的...希望它对其他人有帮助。

In my case, I was using MVC and I just wanted the page to refresh a few seconds after the download button was selected in order to show the new download count. I was returning the file from the controller.

To do this I simply changed the view by adding an onclick event to the download button that called the following script (also in the view):

setTimeout(function () {
        window.location.reload(1);
    }, 5000);

It fit my purpose... hope it helps someone else.

雨落星ぅ辰 2024-10-06 03:28:03

如果需要的话,这是快速且容易破解的。

第 1 步: 将隐藏按钮添加到 .aspx 页面:

<asp:Button ID="btnExportUploaded" runat="server" Text="Button" style="visibility:hidden"  OnClick="btnExportUploaded_Click" CssClass="btnExportUploaded" />

第 2 步: 执行默认的回发操作,最后使用 jquery 调用注册一个启动脚本,该脚本将触发隐藏按钮单击并下载文件:

ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(this.GetType(), "modalstuff", "$('.btnExportUploaded').click();", true);

This is quick and easy to hack if needed.

Step 1: Add hidden button to .aspx page:

<asp:Button ID="btnExportUploaded" runat="server" Text="Button" style="visibility:hidden"  OnClick="btnExportUploaded_Click" CssClass="btnExportUploaded" />

Step 2: Perform your default postback action and at the end register a startup script with jquery call which will trigger the hidden button click and cause a file to download:

ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(this.GetType(), "modalstuff", "$('.btnExportUploaded').click();", true);
甜柠檬 2024-10-06 03:28:03

一种更简单的方法是只执行 PostBack 事件中所需的任何操作,并使用附加参数注册重新加载脚本来指示下载。
类似于:

C# 代码:

protected void SaveDownloadCount(int downloadId)
{
    // Run in a PostBack event. 
    // 1) Register download count, refresh page, etc.
    // 2) Register a script to reload the page with an additional parameter to indicate the download. 
    Page.ClientScript.RegisterStartupScript(GetType(), "download",
        "$(document).ready(function(){window.location.href = window.location.pathname + window.location.search ? '&' : '?' + 'printId={0}';});".Replace("{0}", downloadId.ToString()), true);
}

然后,在 PageLoad 中,我们需要检查下载参数并提供文件:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int printId;
            if (Request.QueryString["printId"] != null && int.TryParse(Request.QueryString["printId"], out printId))
            {
                // Check if the argument is valid and serve the file. 
            }
            else
            {
                // Regular initialization
            }
        }
    }

这与 @puddleglum 答案类似,但没有“不同步”超时的缺点。

A simpler approach is to just do whatever needed in the PostBack event, and register a reload script with an additional argument to indicate the download.
Something like:

C# code:

protected void SaveDownloadCount(int downloadId)
{
    // Run in a PostBack event. 
    // 1) Register download count, refresh page, etc.
    // 2) Register a script to reload the page with an additional parameter to indicate the download. 
    Page.ClientScript.RegisterStartupScript(GetType(), "download",
        "$(document).ready(function(){window.location.href = window.location.pathname + window.location.search ? '&' : '?' + 'printId={0}';});".Replace("{0}", downloadId.ToString()), true);
}

Then, in PageLoad we need to check for the download paramenter and serve the file:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int printId;
            if (Request.QueryString["printId"] != null && int.TryParse(Request.QueryString["printId"], out printId))
            {
                // Check if the argument is valid and serve the file. 
            }
            else
            {
                // Regular initialization
            }
        }
    }

This is simalar to @puddleglum answer but without the drawback of the "out of synch" timeout.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文