使用Jquery Ajax下载文件

时间:2014-08-28 10:16:13

标签: c# jquery asp.net-mvc

我使用jquery Ajax下载PDF文件,我在运行时生成PDF并下载它, 这是我的Ajax调用

  $.ajax({
            async: "false",
            type: "POST",
            url: "/Reports/DownloadFile?userId=" + encodeURIComponent(userId) + "&date=" + encodeURIComponent(date),
            success: function (result) {
            }
        });

这就是我在ActionResult中所做的事情

 public FileContentResult DownloadFile(int userId, string date, int rptType)
        {
            var userInfo = UserBLL.GetUserByID(associateId).Name;
            var dtFileDate = Convert.ToDateTime(date);
            var pdfStream = GeneratePDFStream(userId, date);//Generating Stream

if(date < DateTime.Now)
{       
return File(pdfStream, "application/pdf", string.Format("MyReport{0}{1}.pdf", userInfo.Name, dtFileDate.ToShortDateString().Replace("/", "")));
}
return null; 
        }

但它的回归

Sorry, an error occurred while processing your request.

如何使用Ajax调用下载文件?请注意,我不能使用jquery FileDownload,但我可以不使用Ajax调用,请建议 我也试过这个,但同样的错误

 var url = "/Reports/DownloadFile?userId=" + encodeURIComponent(userId) + "&date=" + encodeURIComponent(date);

        window.open(url);

1 个答案:

答案 0 :(得分:0)

而不是ajax调用,只需尝试使用Iframe作为(演示代码):

var url = "/Reports/DownloadFile?userId=" + encodeURIComponent(userId) + "&date=" + encodeURIComponent(date) ;

var $dialog = $('<div></div>')
             .html('<iframe style="border: 0px; " src="' + url + '" width="850px" height="100%" scrolling="no"></iframe>')
              .dialog({
                  autoOpen: false,
                  modal: true,
                  height: 625,
                  width: 850,
                  title: 'YourPdfFile'
              });
        $dialog.dialog('open');