我正在努力解决下载从后端发送的pdf文件的问题。
我得到一个blob响应,但是当我下载并打开它时,我看到空工作表,其数量与应该的工作表数量相同。有没有可能是编码问题?
目前,后端返回给我一个UTF-8格式的PDF,但如果我看看我电脑上的其他PDF文件,它们是ANSI格式的。
后端响应预览:
数据和标题:
空白:
用记事本打开PDF文件:
const receipt = await this.downloadBookingReceipt({
bookingNumber: this.bus.bookingReference,
receiptFormat: 'pdf',
});
/**
* Using "file-saver" library
*/
const blob = new Blob([receipt.data], { type: 'application/pdf' });
saveAs(blob, 'receipt.pdf', { autoBom: true });
/**
* Using <a>
*/
const pdfData = new Blob([receipt], { type: 'application/pdf' });
// Create a link pointing to the ObjectURL containing the blob.
const pdfUrl = window.URL.createObjectURL(pdfData);
// window.open(pdfUrl);
const downloadLink = document.createElement('a');
downloadLink.href = pdfUrl;
downloadLink.download = `${this.bus.bookingReference}-receipt.pdf`;
downloadLink.click();
setTimeout(function () {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(pdfUrl);
}, 100);
下面是downloadBookingReceipt函数:
static async downloadBookingReceipt (axios, { bookingNumber, receiptFormat }) {
return await axios.get(
`/v1/booking/${bookingNumber}/receipt/${receiptFormat}`, {
responseType: 'blob',
}
);
}
和该端点的服务器处理程序:
/**
* Handler for the booking receipt
*/
const { data } = await axios.get(BASE_URL + req._parsedUrl.path, {
headers: {
AccessToken: TOKEN,
},
});
res.setHeader(
'content-disposition',
`attachment; filename="${req.url.slice(9, 18)}-receipt.pdf"`
);
res.setHeader('Content-Type', 'application/pdf');
res.end(data);
/** */
1条答案
按热度按时间5n0oy7gb1#
我是这样解决我的问题的: