通过ajax调用ASP MVC下载PDF文件

Mok*_*bli 1 ajax asp.net-mvc

我尝试下载一个pdf文件按钮点击通过ajax调用使用ASP MVC模型当我点击我的按钮,什么都没发生,但当我在网址上添加控制器方法我的文件下载.我只想在按钮点击下载它

JS:

$('#PrintTimeSheet').click(function () {
            $.ajax({
                type: 'POST',
                url: "/Home/DownloadFile",
                success: function (response) {
                }
            });
});
Run Code Online (Sandbox Code Playgroud)

控制器:

public FileResult DownloadFile()
{
    Document PDF = new Document();
    MemoryStream memoryStream = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(PDF, memoryStream);
    PDF.Open();
    PDF.Add(new Paragraph("Something"));
    PDF.Close();
    byte[] bytes = memoryStream.ToArray();
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment;filename=Receipt-test.pdf");
    Response.BinaryWrite(memoryStream.ToArray());
    return File(bytes, "application/pdf");
}
Run Code Online (Sandbox Code Playgroud)

teo*_*kot 5

不要使用Ajax下载文件.你可以在这个问题中看到它真的很棘手.

不管怎样,最好使用GETwindow.location.href导致文件下载异步.

$('#PrintTimeSheet').click(function () {
   window.location.href = "/Home/DownloadFile";
});

[HttpGet]
public FileResult DownloadFile()
{
   //your generate file code
}
Run Code Online (Sandbox Code Playgroud)