关于前端:vue中本地文件下载

6次阅读

共计 576 个字符,预计需要花费 2 分钟才能阅读完成。

1. 先把文件放在动态资源 public 中

2. 给标签增加点击事件

<a id="download" href="javascript:void(0);" @click="download"> 下载模板 </a>

3. 页面中引入 axios

import axios from 'axios';

4. 为了防止中文无奈导出,将待导出文件名称改为英文“peoplecode.xls”,导出后的名称设置为中文名称“员工工号.xls”;

download () {          
    axios.get('file/peoplecode.xls', {   // 动态资源文件夹 public            
        responseType: 'blob',          
    }).then(response => {const url = window.URL.createObjectURL(new Blob([response.data]));            
        const link = document.createElement('a');            
        let fname = '员工工号.xls';            
        link.href = url;            
        link.setAttribute('download', fname);            
        document.body.appendChild(link);            
        link.click();}).catch(error => {console.log('error:'+JSON.stringify(error))          
    });        
},
正文完
 0