ASP.NET通过事件处理程序的JavaScript客户端添加文件下载 [英] ASP.NET Downloading file through client javascript added in EventHandler

查看:186
本文介绍了ASP.NET通过事件处理程序的JavaScript客户端添加文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是很熟练的ASP.NET和我曾试图:

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


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

和这个按钮服务器控件:

and this Button server control:

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

在事件处理我只需拨打:

in the EventHandler I simply call:

//更新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...

推荐答案

所有房间都用 MyDownloadHandler.ashx 头做的。如果添加有这个头在你的处理器的ashx

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.

,你只用JavaScript做的就是

And you only have to do with javascript is

window.location = "MyDownloadHandler.ashx";

或只是一个简单的链接。

or just a simple link.

总结一下,你必须创造出很多code那是没有必要的,你做和后回首,那也是没有必要的。

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.

相对:
<一href=\"http://stackoverflow.com/questions/10912164/what-is-the-best-way-to-download-file-from-server/10912955\">What是从服务器下载结果文件的最佳途径
<一href=\"http://stackoverflow.com/questions/14609389/error-handling-when-downloading-file-from-asp-net-web-handler-ashx/14616216\">Error从的ASP.NET Web处理程序(ashx的)

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

这篇关于ASP.NET通过事件处理程序的JavaScript客户端添加文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆