2012-08-23 25 views
8

我正在从母版页客户端脚本(Jquery)请求.ashx页面,它具有下载PDF文件的代码。当我调试它时,我可以看到“文件下载”代码的执行情况,但文件没有下载。通过调用.ashx文件下载页面

$.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

此主题可能对您有帮助吗? http://stackoverflow.com/questions/1999607/download-and-open-pdf-file-using-ajax –

回答

11

你的文件被下载,但你得到它的JavaScript,您的呼叫的data参数,因为你用Ajax调用它。

使用处理 - 所以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

+0

这是非常有益的,你是对的答案。几分钟后,试图在客户端用json调用下载.ashx中的文件,但我没有以任何方式获取该文件。 – amelian

+0

@Aristos这个完美的作品。但是,如果服务器端出现问题,我需要显示该消息。我该怎么做?消息“出现错误或文件未找到” – Prabu

+0

@Prabu在服务器端,您只能记录处理程序中相对容易的错误。查找或写一个日志类... – Aristos