通过调用.ashx页面进行文件下载

9

我正在使用客户端脚本(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();
    }

1
这篇帖子有帮助吗?https://dev59.com/GnI-5IYBdhLWcg3wI0x9 - Neil Thompson
1个回答

15

你的文件正在下载,但你通过Ajax调用时可以在调用的data参数上获取它。

你使用了一个处理器 - 所以这里不需要使用ajax,而使用javascript最简单的方法是:

window.location = "FileDownload.ashx?parametres=22";

或者使用一个简单的链接,如:

  <a target="_blank" href="FileDownload.ashx?parametres=22" >download...</a>
啊,通过URL发送参数,你不能像那样进行发布。
你还可以阅读:What is the best way to download file from server

这非常有帮助,你的答案是正确的。在客户端使用json调用尝试下载一个.ashx文件几分钟后,我无论如何都没有得到文件。 - amelian
@Aristos 这个完美地运行了。但是如果服务器端出现问题,我需要显示消息。我该怎么做?消息是“出现错误或文件未找到”。 - Praburaj
@Prabu,在服务器端,你只能记录错误 - 在处理程序内相对容易。找到或编写一个日志类... - Aristos
1
@Aristos 但是如果出现问题,我需要通知客户。 - Praburaj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接