【发布时间】:2018-06-19 20:40:54
【问题描述】:
我有一个 NodeJS-ExpressJS 服务器(用于托管网页)和 Django API 服务器。当从 ExpressJS 服务器调用 Django 服务器中的特定端点时(当用户单击网页上的按钮时),将生成 PDF。我想将此 PDF 从 Django 服务器发送到 ExpressJS 服务器,然后将其下载到用户的浏览器(用户仅与 ExpressJS 服务器交互)。为了做到这一点,我在 Django 服务器中将 PDF 编码为 base64 字符串,并在 HTTP 响应中返回该字符串。在 ExpressJS 服务器中,我对 base64 字符串进行解码,然后使用 ExpressJS 框架提供的res.download() 方法将 PDF 下载到用户的浏览器。此方法似乎有效,但它会损坏 PDF 文件吗?有没有办法简单地将 PDF 文件作为二进制文件发送并以这种方式下载到浏览器(如果可能,请提供示例)?非常感谢任何答案、示例和建议。
Django API server
def process_upload(request):
'''
Process request and generate PDF
....
'''
with open(pdf, "rb") as pdf_file:
encoded_string = base64.b64encode(pdf_file.read())
return HttpResponse(encoded_string)
ExpressJS server
server.get('/api', function(req, res, next) {
request.post({
url: 'http://<api_url>',
oauth: oauth,
preambleCRLF: true,
postambleCRLF: true
}, function(error, response, body){
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="file.pdf"'
});
});
const download = Buffer.from(body.toString('utf-8'), 'base64');
res.end(download);
});
【问题讨论】:
标签: python node.js django express pdf