通過swagger下載的文檔以及將接口接到前端下載都會亂碼;但是有一種情況不會亂碼,就是直接使用后台的接口地址,也就是說直接使用a標簽就不會出現亂碼的問題,可是 直接使用a標簽,會顯着代碼不優雅。所以,有了以下解決辦法。
// 導入功能中的下載模板功能 downMoudle() { downloadModule().then(res => { const url = window.URL.createObjectURL( new Blob([res.data], { type: 'application/octet-stream' }) ) const link = document.createElement('a') link.href = url link.setAttribute( 'download', res.headers['content-disposition'].split('filename=')[1] ) link.click() }) }, // 導出 handleCommand(command) { exportList2(this.multipleSelection).then(res => { const url = window.URL.createObjectURL( new Blob(['\ufeff' + res.data], { type: 'application/octet-stream' }) ) const link = document.createElement('a') link.href = url link.setAttribute( 'download', res.headers['content-disposition'].split('filename=')[1] ) link.click() } }
以下的這段代碼也可以實現下載功能,但是我使用下面的代碼,會導致下載下來的文件亂碼,
有需求的伙伴也可以使用下面的代碼試一下
downMoudle() { downloadModule().then(res => { const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) const url = window.URL || window.webkitURL || window.moxURL const downloadHref = url.createObjectURL(blob) const downloadLink = document.createElement('a') console.log(downloadLink) downloadLink.href = downloadHref downloadLink.download = '模板.xls' downloadLink.click() console.log(downloadHref) }) },