首页 > 解决方案 > Nginx“X-Accel-Redirect”以明文形式提供pdf

问题描述

我在使用 .pdf 文件在浏览器上显示时遇到问题X-Accel-Redirect。直接从 Nginx 公共位置链接文件 URL 效果很好。X-Accel-Redirect但是,通过添加“内部”并从 Django调用来限制对该位置的访问,HttpResponse()将 pdf 文件作为纯文本发送,就像任何其他静态文件(css、js、html)一样。

蟒蛇响应

response = HttpResponse()
response['Content-Type'] = 'application/pdf'
response['Content-Disposition'] = 'attachment; filename=example.pdf'
response['X-Accel-Redirect'] = '/media/file-pdf/example.pdf'
return response

Nginx 位置

location /media/{
    internal;
    alias /var/www/media/;
    default_type application/pdf;
}

Javascript

$.ajax({
        url: http://www.example.com/pdf-api/,
        type: 'GET',
        success: function(data) {
            window.open(data);
            console.log(data);
        },
});

接收到的文本形式的示例 pdf(如在浏览器控制台上所见)

%PDF-1.3
%“Œ‹ž ReportLab Generated PDF document http://www.reportlab.com
1 0 obj
<<
/F1 2 0 R
>>
endobj
2 0 obj
<<
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
>>
endobj
3 0 obj
<<
/Contents 7 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 6 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<

>> 
  /Type /Page
>>
endobj
4 0 obj
<<
/PageMode /UseNone /Pages 6 0 R /Type /Catalog
>>
endobj
5 0 obj
<<
/Author (anonymous) /CreationDate (D:20180925202407-08'00') /Creator (ReportLab PDF Library - www.reportlab.com) /Keywords () /ModDate (D:20180925202407-08'00') /Producer (ReportLab PDF Library - www.reportlab.com) 
  /Subject (unspecified) /Title (untitled) /Trapped /False
>>
endobj
6 0 obj
<<
/Count 1 /Kids [ 3 0 R ] /Type /Pages
>>
endobj
7 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 856
>>

我的问题是:向使用 Python + Django + Nginx 的用户提供受限 pdf(或任何文件)的正确方法是什么?或者我应该在浏览器端将发送的二进制数据转换为pdf?

标签: javascriptdjangopdfnginxx-accel-redirect

解决方案


我认为你所做的是正确的。浏览器不能仅仅“显示” PDF 文件本身。我相信您可能指的是 Chrome 在您打开 PDF 文件时自动显示它们?实际上,这些是由前端的下载触发的。

在您的 AJAX 调用从后端收到 PDF 后,您可以从这里获得一些选择:

  1. 在您的 UI 中嵌入 PDF 查看器并将 PDF 的 URL 传递给查看器(例如ViewerJSpdf.js)。

  2. 使用数据创建一个Blob并将其作为 href 附加到隐藏的锚标记并使用 javascript 对其强制click()执行操作以触发下载。你可能会在这里找到一些灵感


推荐阅读