【问题标题】:file download by calling .ashx page通过调用 .ashx 页面下载文件
【发布时间】:2012-08-18 16:45:12
【问题描述】:

我从母版页客户端脚本 (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();
    }

【问题讨论】:

标签: asp.net jquery ashx


【解决方案1】:

您的文件正在下载,但您在 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

【讨论】:

  • 这很有帮助,你的答案是对的。几分钟后尝试在客户端通过 json 调用下载 .ashx 中的文件,但我没有以任何方式获取该文件。
  • @Aristos 这非常有效。但是如果服务器端出现问题,我需要显示消息。我该怎么做?消息“出现问题或找不到文件”
  • @Prabu 在服务器端,您只能记录错误 - 在处理程序中相对容易。查找或编写日志类...
  • @Aristos 但是如果出现问题我需要通知客户
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-13
  • 1970-01-01
  • 2011-05-26
  • 2014-10-22
相关资源
最近更新 更多