Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...