Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
800 views
in Technique[技术] by (71.8m points)

asp.net mvc - return PDF in ajax request

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");
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...