//如果后端返回的是文件流而不是下载地址,前端需要设置处理,创建下载链接
<button @click="eventDocDownInfo()">Download File</button>
async function eventDocDownInfo() {
try {
// const response: any = await eventDocDown()//或者在自己的接口组件中设置下列需要设置的属性
const response = await axios({
method: 'get',
url: 'http://localhost:3000/download',
responseType: 'blob' // 非常重要,确保返回的是 Blob 类型 responseType 为 blob:这是关键一步,确保 Axios 将响应作为 Blob 对象处理,这样我们可以创建下载链接。
});
const url = window.URL.createObjectURL(new Blob([response]))
const link = document.createElement("a")
link.href = url
link.setAttribute("download",'downloaded-file.pdf')//导出的格式一定要和接口返回的文件一致
document.body.appendChild(link)
link.click()
window.URL.revokeObjectURL(url)
document.body.removeChild(link)
} catch (error) {
console.error('Error downloading the file:', error);
}
}