我用来构建一个响应 application-json
mime 类型的网络服务。
但现在我想以字节形式响应 PDF,所以我假设我必须更改 mime 类型。
我将使用路由,但我也可以使用 flask-restful。
下面的代码显示了结构,但我不知道如何将pdf转换为字节然后发送。
@app.route('/pdf/myfile')
def pdf():
data = open("myfile.pdf", "rb").read()
# make a reponse with those bytes
return response
在客户端(angular.js
)我会有这个:
$http.get('/pdf/myfile', null, { responseType: 'arraybuffer' })
.success(function (data) {
var file = new Blob([data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
最佳答案
您可以使用 send_file
或 send_from_directory
:
from flask import send_from_directory
@app.route('/pdf/myfile')
def pdf():
return send_from_directory('/dir/of/pdf', 'my.pdf')
默认情况下,这将发送内联文件,浏览器可能会呈现 PDF 本身。如果您设置 as_attachment=True
,文件将作为附件显示,浏览器将弹出“另存为”对话框。
send_file
让您可以更好地控制 mime 类型和缓存等内容。默认值应该可以正常工作。
关于javascript - python - 在网络服务中以字节形式发送 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35339396/