ASP.NET Downloading file through client javascript added in EventHandler

北城以北 提交于 2019-12-11 09:58:04

问题


I am not very skilled in ASP.NET and I have tried to:

  1. Update UI elements on an aspx site
  2. at the same time download a file

I have this JS function:

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;
        };

and this Button server control:

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

in the EventHandler I simply call:

// UPDATE UI

textBoxXY.Text = "Text after file download";

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

What do you think of this approach. It seems to work but...


回答1:


All have to do with the MyDownloadHandler.ashx headers. If you add there this headers on your handler ashx

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

then the browser will open the file save browser and not a new tab.

And you only have to do with javascript is

window.location = "MyDownloadHandler.ashx";

or just a simple link.

So to summarize, you have create a lot of code that is not necessary, and you make and a post back, that is also not necessary.

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



来源:https://stackoverflow.com/questions/18087771/asp-net-downloading-file-through-client-javascript-added-in-eventhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!