jQuery 通过调用.ashx页面下载文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12087040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
file download by calling .ashx page
提问by dotnetrocks
I'm requesting .ashx page from Master page client side script (Jquery) which has a code to download a PDF file. When I debug it, I can see the execution of "file download" code but file is not downloading.
我正在从母版页客户端脚本 (Jquery) 请求 .ashx 页面,该脚本具有下载 PDF 文件的代码。当我调试它时,我可以看到“文件下载”代码的执行,但文件没有下载。
$.ajax({
type: "POST",
url: "FileDownload.ashx",
dataType: "html",
success: function (data) { }
} );
public class FileDownload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
string fileName = "BUSProjectCard.pdf";
string filePath = context.Server.MapPath("~/Print/");
context.Response.Clear();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("Content-Disposition", "attachment; filename="+fileName);
context.Response.TransmitFile(filePath + fileName);
context.Response.End();
}
回答by Aristos
Your file is downloading, but you get it on javascript, on the data
parameter of your call because you call it with Ajax.
您的文件正在下载,但您在 javascript 上获取它,在data
您的调用参数上,因为您使用 Ajax 调用它。
You use a handler - so ajax not needed here, and the most easy thing to do using javascript is that:
您使用处理程序 - 所以这里不需要 ajax,使用 javascript 最简单的事情是:
window.location = "FileDownload.ashx?parametres=22";
or with a simple link as
或者用一个简单的链接作为
<a target="_blank" href="FileDownload.ashx?parametres=22" >download...</a>
Ah, and send the parameters via the url, you can not post them that way.
啊,通过url发送参数,你不能那样发布它们。
You can also read: What is the best way to download file from server
您还可以阅读:从服务器下载文件的最佳方式是什么