【问题标题】:How can I call an MVC action to download a PDF file?如何调用 MVC 操作来下载 PDF 文件?
【发布时间】:2016-11-04 13:54:59
【问题描述】:

我称它为创建内存 PDF 文件的 MVC 操作。我想在完成操作后立即返回文件并下载。

调用 MVC 动作的 Ajax 代码

function convertToPDF() {
        $.ajax({
            url: "/Tracker/ConvertPathInfoToPDF",
            type: "GET",
            data: JSON.stringify({ 'pInfo': null }),
            dataType: "json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            success: function (data) {

            },
            error: function () {
                alert("Unable to call /Tracker/ConvertPathInfoToPDF");
            }
        });
    }

MVC 动作

public FileResult ConvertPathInfoToPDF(PositionInfo[] pInfo)
    {
        MemoryStream fs = new MemoryStream();
        //FileStream fs = new FileStream(@"C:\Test.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
        Rectangle rec = new Rectangle(PageSize.A4);
        Document doc = new Document(rec);
        PdfWriter writer = PdfWriter.GetInstance(doc, fs);
        doc.Open();
        doc.Add(new Paragraph("Hamed!"));
        doc.Close();

        return File(fs, System.Net.Mime.MediaTypeNames.Application.Octet, "Test.pdf");
    }

MVC 操作完全运行,但我在浏览器中收到以下错误:

加载资源失败:服务器响应状态为 500(内部服务器错误)

【问题讨论】:

标签: c# ajax file model-view-controller download


【解决方案1】:

MVC 动作:

public FileResult ConvertPathInfoToPDF(PositionInfo[] pInfo)
    {
        MemoryStream fs = new MemoryStream();
        Rectangle rec = new Rectangle(PageSize.A4);
        Document doc = new Document(rec);
        PdfWriter writer = PdfWriter.GetInstance(doc, fs);
        doc.Open();
        doc.Add(new Paragraph("Hamed!"));
        doc.Close();

        byte[] content = fs.ToArray(); // Convert to byte[]

        return File(content, "application/pdf", "Test.pdf");
    }

调用 MVC 动作的 Ajax 代码:

function convertToPDF() {
        window.location = '/Tracker/ConvertPathInfoToPDF?pInfo=null';
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 2017-06-10
    • 1970-01-01
    • 2022-11-12
    • 2011-11-26
    • 2016-01-10
    相关资源
    最近更新 更多