Vue下载本地pdf、word、excel文件

451 阅读1分钟

在项目中需要对pdf、word、excel等文档的下载,也就是获取文件的静态路径,下载到本地。

方案 :利用 axios 下载

axios.get('resource/设备运行报告.pdf',{
    headers:{
        Authorization: localStorage.getItem('Authorization'),
    },
    responseType: 'blob',
}).then(res => {
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    let fileName = "设备运行报告.pdf" //保存到本地的文件名称
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    console.log(link);
    link.remove();
})

注意: 文件存放的位置很重要,放错的话,会获取不到本地文件的。

网上查到资料描述是:

Vue2中的静态资源在 static
Vue3中的静态资源则在 public

我的文件放到了这里resource下可以读到

image.png