【问题标题】:Unable to download PDF in MVC无法在 MVC 中下载 PDF
【发布时间】:2015-10-06 00:26:26
【问题描述】:

我创建了一个方法,用于创建 pdf 并将其保存到项目中的目录中。但是,我无法在创建此文件后下载该文件。我已经尝试了几个我在堆栈溢出和许多其他站点上看到的选项。我可以在 firebug 的响应中看到 PDF 内容,我可以手动打开文件,但没有文件下载。请帮忙。

控制器

    public class SignatureController : Controller
    {
    // GET: Signature
    public FileContentResult Index(string orderNumber)
    {
        var pdfFile = DocumentGenerator.GenerateSignedDocument(orderNumber);

        byte[] filedata = System.IO.File.ReadAllBytes(pdfFile);
        string contentType = MimeMapping.GetMimeMapping(pdfFile);

        System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
        {
            FileName = pdfFile,
            Inline = true,
        };

        Response.AppendHeader("Content-Disposition", cd.ToString());

        return File(filedata, contentType);
    }
}

PDF 生成器

        public static string GenerateSignedDocument(string orderNumber)
        {

      ...............

        string currentDate = DateTime.Now.ToString("MMddyyyy");

        string fileName = HostingEnvironment.MapPath(pdfTempPath) + orderNumber + currentDate + ".pdf";

        pdfDocument.Save(fileName);
        return fileName;
    }

标题正在返回

缓存控制
私人的 内容处置 附件;文件名="签名文件.pdf" 内容编码
压缩包 内容类型
申请/pdf 日期
格林威治标准时间 2015 年 7 月 16 日星期四 16:58:29 服务器
微软-IIS/8.0 传输编码
分块 变化
接受编码 X-AspNet-版本
4.0.30319 X-AspNetMvc-版本 5.2 X-Powered-By
ASP.NET X-SourceFiles
=?UTF-8?B?QzpcVXNlcnNccmphbWVzXFNvdXJjZVxXb3Jrc3BhY2VzXEN1c3RvbWVyUGlja1VwXEN1c3RvbWVyUGlja1VwLldlYlxTaWduYXR1cmVcSW5kZXg =?=

【问题讨论】:

    标签: asp.net-mvc-4 pdf iis


    【解决方案1】:

    Inline 设置为false 或省略它。这样标题是attachment(而不是inline)。

    例如(此示例下载文件系统中的文件)

    public FilePathResult DownloadPdf()
    {
        var cd = new System.Net.Mime.ContentDisposition
        {
            FileName = "foo.pdf"
            //Inline = false //false or omit
        };
    
    
        Response.AppendHeader("Content-Disposition", cd.ToString());
        return File("~/files/somefile.pdf", "application/pdf");
    }
    

    标题看起来像:Content-Disposition:attachment; filename=foo.pdf


    文件名是您设置的 - 示例从文件系统获取 pdf 只是因为我没有即时生成一个(因此您的代码适用于 byte 结果)。关键是返回正确的标题attachment - 你甚至可以手动设置

    Response.AppendHeader("Content-Disposition", "attachment; filename=" + pdfFile);
    

    并且不必使用System.Net.Mime.ContentDisposition。顺便说一句,您的 pdfFile 变量是字符串吗(您将其用作 FileName 属性)?

    第...

    【讨论】:

    • 还是不行。 FileName 是否需要是文件的确切名称,或者只是您想要它说的名称。如果放置 Process.Start(pdfFile); ,我可以在本地打开文档;在本地,但在部署到 iis 时不会
    • @Rickjames 查看更新 - 我怀疑您的 pdfFile 变量有问题 - 您将其设置为 文件名 (但我可以看到您正在做 @ 987654335@就可以了)
    • 仍然没有运气...查看更新以了解标头返回的内容。
    猜你喜欢
    • 2021-04-29
    • 2013-06-03
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    相关资源
    最近更新 更多