我正在尝试从api响应下载pdf文件,api将该文件作为附件返回,
def function():
file = ReportFileHandler.read_file(current_doc.name)
file_data = file['Body'].read()
response = make_response(file_data)
response.headers['Content-Type'] = file['ContentType']
response.headers['Content-Disposition'] = "attachment;filename=%s" % current_doc.name
response.headers['Access-Control-Expose-Headers'] = 'Content-Disposition'
return response
我在下面尝试的js代码中
base64ToArrayBuffer(data) {
var binaryLen = data.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = data.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
},
async model(){
const apiService = this.get('apiService');
try{
let response = await apiService.get(`report/${81}/document/${14}/?format=pdf`);
var arrBuffer = base64ToArrayBuffer(response);
var newBlob = new Blob(arrBuffer, {type: "application/pdf"})
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(newBlob);
var link = document.createElement('a');
link.href = data;
link.download="file.pdf";
link.click();
console.log(response);
}catch(error){
console.log(error);
}
},
,但它正在下载空的pdf文件,或者有时会给pdf加载错误。