下载pdf
下载pdf
以下是一个通用的下载 PDF 文件的示例
async function downloadPDF(url, orderNo, headers, downloadFileName, downloadElementRef) {
try {
const response = await axios.get(`${url}?orderNo=${orderNo}`, {
headers,
responseType: 'blob' // 设置响应类型为 'blob'
});
if (response.headers['content-type'] === 'application/pdf') {
console.log('You can download the PDF');
const blob = new Blob([response.data], { type: 'application/pdf' });
const downloadUrl = window.URL.createObjectURL(blob);
if (downloadElementRef) {
downloadElementRef.href = downloadUrl;
downloadElementRef.download = downloadFileName;
downloadElementRef.click();
}
}
} catch (error) {
console.log('Failed to download PDF', error);
}
}
// Usage example
const tempUrl = 'https://example.com/api/download';
const orderNo = '123456';
const headers = { Authorization: 'Bearer token' };
const downloadFileName = 'downloadBill.pdf';
const downloadElementRef = document.createElement('a'); // You can use a Vue ref or any other method to get the reference
downloadPDF(tempUrl, orderNo, headers, downloadFileName, downloadElementRef);
这个函数 downloadPDF 接受五个参数:
url:请求的 URL。orderNo:订单号参数。headers:请求头。downloadFileName:下载的文件名。downloadElementRef:用于触发下载的 DOM 元素引用。
你可以将这个函数集成到你的项目中,并根据需要传入相应的参数来下载 PDF 文件。这种方法可以有效地避免泄露公司数据,同时保持代码的通用性。
之前下载的内容为空,虽然下载了pdf
原因是没给 responseType:blob
const response = await axios.get(`${url}?orderNo=${orderNo}`, {
headers,
responseType: 'blob' // 设置响应类型为 'blob'
});

浙公网安备 33010602011771号