ASP.NET通过在EventHandler中添加的客户端javascript下载文件 [英] ASP.NET Downloading file through client javascript added in EventHandler
问题描述
- 在aspx网站上更新UI元素
- 同时下载文件
我有这个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 =serverID =Button1Content =DOWNLOADOnClick =Button1_Click/>
在EventHandler中我只是调用:
// UPDATE UI
textBoxXY.Text =文件下载后的文本;
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 Handler(.ashx)下载文件时出错处理
I am not very skilled in ASP.NET and I have tried to:
- Update UI elements on an aspx site
- 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...
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)
这篇关于ASP.NET通过在EventHandler中添加的客户端javascript下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!