ASP.NET通过EventHandler中添加的客户端javascript下载文件

ASP.NET Downloading file through client javascript added in EventHandler

本文关键字:客户端 javascript 下载 文件 添加 NET 通过 EventHandler ASP      更新时间:2023-09-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;
        };

和这个按钮服务器控制:

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

在EventHandler中,我简单地调用:

//更新UI

textBoxXY.Text = "Text after file download";
ClientScript.RegisterStartupScript(typeof(MyPage), "myDownloadKey", "downloadURL(" + ResolveUrl("~/MyDownloadHandler.ashx") + ");", true);

你觉得这种方法怎么样。它似乎有效,但是。。。

所有这些都与MyDownloadHandler.ashx标头有关。如果你在你的处理程序ashx 上添加这个标题

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

则浏览器将打开文件保存浏览器,而不是新的选项卡。

你只需要做javascript就是

window.location = "MyDownloadHandler.ashx";

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

总之,你已经创建了很多不必要的代码,你制作了一个帖子,这也是不必要的。

相对:从服务器下载文件的最佳方式是什么
从ASP.NET Web处理程序(.ashx)下载文件时的错误处理