【问题标题】:Failed to load PDF document in web api无法在 web api 中加载 PDF 文档
【发布时间】:2016-08-27 01:03:47
【问题描述】:

我在下载和打开 pdf 文件时遇到错误

加载 PDF 文档失败

。但是当我尝试下载 txt 文件时,它会完全下载成功。我需要将此 ajax 请求作为 POST 方法,因此在互联网上搜索后,我找到了此代码。

$.ajax({
type: "POST",
url: url,
cache: false,
contentType: false,
processData: false,
success: function (data) {

    var blob = new Blob([data]);
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = textName;
    link.click();
}, error: function (data) { alert("error"); }});

我使用 web api 来下载文件

public HttpResponseMessage Download(string fileName)
{   
    string filePath = Path.Combine(PATH, fileName.Replace('/', '\\'));
    byte[] pdf = System.IO.File.ReadAllBytes(filePath);
    HttpResponseMessage result = Request.CreateResponse(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(pdf);
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = "MyPdf.pdf";
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    return result;
}

请帮帮我

【问题讨论】:

  • 如果你在Blob构造函数中指定了mime类型呢? var blob = new Blob([data], { type: 'application/pdf' });
  • 是的,我也试过 :(
  • 你用的是什么浏览器?错误是在哪一行抛出的?
  • 我正在使用 Google chrome。下载时我没有收到任何错误。 Pdf 文件被下载并在打开时显示错误 Failed to Load PDF

标签: c# jquery asp.net asp.net-web-api dotnetnuke


【解决方案1】:

引用Download pdf file using jquery ajax

jQuery 在使用 AJAX 请求加载二进制数据时存在一些问题,因为它 尚未实现一些 HTML5 XHR v2 功能

它提供了两个选项供您尝试。我不会在这里重复它们,因为它们属于那个答案。检查链接。

在服务器端,我已经使用这种方法成功下载了 PDF 文件。

[HttpPost]
public HttpResponseMessage Download(string fileName)
{   
    string filePath = Path.Combine(PATH, fileName.Replace('/', '\\'));
    byte[] pdf = System.IO.File.ReadAllBytes(filePath);
    //content length for header
    var contentLength = pdf.Length;
    var statuscode = HttpStatusCode.OK;
    var result = Request.CreateResponse(statuscode);
    result.Content = new StreamContent(new MemoryStream(buffer));
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    result.Content.Headers.ContentLength = contentLength;
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = "MyPdf.pdf";

    return result;
}

与您的原版没有太大不同。

如果您从磁盘/数据库读取或动态生成文件,您还应该检查以确保服务器上的原始文件没有损坏。

【讨论】:

    【解决方案2】:

    问题可能是您的 Content-Disposition 标头。你需要内联,但你有附件。

    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
    

    你现在告诉浏览器专门直接发送文件,并且永远不要尝试在浏览器中显示它。当您执行此操作时,Chrome 的内部 PDF 查看器当前会阻塞。

    更多:Content-Disposition:What are the differences between "inline" and "attachment"?

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 2018-01-10
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      相关资源
      最近更新 更多