【问题标题】:ASP.NET Downloading file through client javascript added in EventHandlerASP.NET 通过在 EventHandler 中添加的客户端 javascript 下载文件
【发布时间】:2020-10-27 20:29:26
【问题描述】:

我对 ASP.NET 不是很熟练,我尝试过:

  1. 在 aspx 网站上更新 UI 元素
  2. 同时下载一个文件

我有这个JS函数:

function downloadURL(url) {
            var hiddenIFrameID = 'hiddenDownloader',
                iframe = document.getElementById(hiddenIFrameID);
            if (iframe === null) {
                iframe = document.createElement('iframe');
                iframe.id = hiddenIFrameID;
                iframe.style.display = 'none';
                document.body.appendChild(iframe);
            }
            iframe.src = url;
        };

还有这个 Button 服务器控件:

<asp:Button runat="server" ID="Button1" Content="DOWNLOAD" OnClick="Button1_Click" />

在 EventHandler 中我简单地调用:

// 更新用户界面

textBoxXY.Text = "Text after file download";

ClientScript.RegisterStartupScript(typeof(MyPage), "myDownloadKey", "downloadURL(" + ResolveUrl("~/MyDownloadHandler.ashx") + ");", true);

您如何看待这种方法。它似乎有效,但是......

【问题讨论】:

  • 但是它会把你带到另一个页面,或者?我需要进行回发以更新 UI 元素。
  • 可能您不需要回发,您可以为要在客户端下载的文件创建参数。但是如果您需要回帖,您可以直接将文件发送给他,而不是重新加载页面。

标签: javascript asp.net onclick download


【解决方案1】:

它们都与MyDownloadHandler.ashx 标头有关。如果您在处理程序 ashx 上添加此标头

 HttpContext.Current.Response.ContentType = "application/octet-stream";
 HttpContext.Current.Response.AddHeader("Content-Disposition", 
                    "attachment; filename=" + SaveAsThisFileName);

然后浏览器将打开文件保存浏览器而不是新标签。

而你只需要使用 javascript 就可以了

window.location = "MyDownloadHandler.ashx";

或者只是一个简单的链接。

总而言之,您创建了很多不必要的代码,并且您进行了回帖,这也没有必要。

亲戚: What is the best way to download file from server
Error handling when downloading file from ASP.NET Web Handler (.ashx)

【讨论】:

  • 好的,但是我在哪里设置 textBoxXY.Text = "文件下载后的文本"; ?那么我将不得不在javascript中做所有这些事情..或者?
  • @PaN1C_Showt1Me 是的,您可以在客户端执行此操作 - 或者您可以执行其他人执行的操作(我避免这样做)以在回发时直接发送文件。或者在页面渲染之后,您只需在脚本区域渲染window.location = "MyDownloadHandler.ashx?id=22"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多