环境:项目通过VUE CLI3 搭建。请求为axios
在本地的文件下载:
将文件传至工程中默认的 public 文件夹中
<a class="btn-link" href="/file/文件名.xlsx" download="自定义文件名.xlsx"> 点击下载 </a>
请求后端,转换后台你返回的二进制流:
HTML:
<button @click="download(/*参数1*/,/*参数2*/)">点击下载</button>
JS:
download (/*参数1*/,/*参数2*/) { let params = { 'id':/*参数1*/, 'fileName': /*参数2*/ } axios.post(/*请求后台地址*/, null, { responseType: 'blob',//声明后端返回的数据为二进制流 transformRequest: [() => { let formData = new FormData() formData.append('params', JSON.stringify(params)) return formData }] }).then(res => { //将二进制流转化为链接 let blob = new Blob([res], { type: 'application/vnd.ms-excel' }) let downloadElement = document.createElement('a') let href = URL.createObjectURL(blob) downloadElement.href = href downloadElement.download = /*自定义文件名*/ document.body.appendChild(downloadElement) downloadElement.click() document.body.removeChild(downloadElement) window.URL.revokeObjectURL(href) }) },