从服务器下载文件的最佳方式是什么 [英] What is the best way to download file from server
问题描述
我有一项有趣的任务,需要我从服务器 (ASP.NET) 将动态生成的文件下载到客户端.在客户端,它只是 JavaScript (jQuery),客户端能够生成大量参数来自定义数据的导出方式.
I have interesting task which requires me to download a dynamically generated file from a server (ASP.NET) to the client. On the client side it is just JavaScript (jQuery) and the client is able to generate a lot of parameters to customize how the data is exported.
从服务器下载文件的最佳方法是什么?我是否应该使用 WCF 服务,例如此处或者像这个这样的简单页面?
What is the best way to do download the file from the server? Should I use a WCF service such as what is described here or simple page like this one?
我不知道如何在不重新加载页面的情况下下载文件(我不确定 $.ajax 在这种情况下是否有效).有人可以就这个主题给我一些指导吗?谢谢.
I don't know how to download a file without reloading the page (I'm not sure that $.ajax will work in this case). Could someone please give me some direction on this topic? Thanks.
推荐答案
首先你可以从处理程序 .ashx
First you can create the file from a handler .ashx
假设您在 download.ashx
有下载文件,并且您有一些参数要从您的 javascript 传递,例如 download.ashx?p1=8827&p2=8831
以了解您要创建的内容.
Let say that you have the file for downloading at download.ashx
and you have some parametres to pass from your javascript, eg download.ashx?p1=8827&p2=8831
to know what you going to create.
然后在您的 javascript 上,您可以简单地将重定向为
Then on your javascript you simple can make a redirect as
window.location = "download.ashx?p1=8827&p2=8831";
或者你可以使用 window.open
来做同样的事情
or alternative you can use the window.open
for do the same think
window.open("download.ashx?p1=8827&p2=8831");
您的文件将开始下载.
只要确保你已经设置了附件的标题,并且在你的句柄上设置了正确的内容类型,例如:
Just make sure that you have set the header of attachment, and the correct contenttype on your handle eg:
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition",
"attachment; filename=" + SaveAsThisFileName);
简单明了,经过测试和工作.
Simple and clear, both tested and working.
您也可能对这个答案感兴趣:如何处理错误.
Also you may interesting on this answer: How to handle errors.
这篇关于从服务器下载文件的最佳方式是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!