return PDF in ajax request

2019-02-06 22:41发布

问题:

I have got an ajax request to my Server where i am creating an PDF File. Now i want to display this file in a new window/tab or just download it. how can i do that?

my request

$.ajax({
    url: '/Document/CreatePDF',
    type: 'POST',
    data: {
        docid: documentId,
        dataId: array
    },
    traditional: true,
    success: function (data) {
    }
});

    [HttpPost]
    public FileStreamResult CreatePDF(long docid, List<long> dataId)
    {
        var document = _rep.LoadDocument(docid.ToString(), Server.MapPath("~/Documents/") + docid + ".xml");

        var exporter = new PDFExporter(document);

        MemoryStream fileStream = exporter.CreatePDF();
        byte[] PdfByte = fileStream.GetBuffer();
        fileStream.Flush();
        fileStream.Close();

        HttpContext.Response.AddHeader("content-disposition","attachment; filename=form.pdf");

        return new FileStreamResult(fileStream, "application/pdf");
    }

回答1:

You cannot use AJAX to download files. The reason for that is because javascript doesn't allow you to save the downloaded content on the client computer, nor to prompt for a Save As dialog. You should use a simple HTML <form> or an anchor:

@using (Html.BeginForm("CreatePDF", "Document", FormMethod.Post, new { id = "myform" }))
{
    <button type="submit">Download</button>
}

If you need to pass arguments to this controller action that are known only at the client you could subscribe to the .submit event of this form and then dynamically inject hidden fields into it with the corresponding values and then leave the default action execute. And if the values are known at the server side you should simply use HTML helpers to generate those hidden fields.