vue實現word,pdf檔案的匯出
阿新 • • 發佈:2019-01-03
vue實現word或pdf文件匯出的功能,我的專案是:後端返回一個文件流(下圖),然後前端對文件流做處理進行下載,程式碼如下:
import axios from 'axios'; axios.get(`url`, { //url: 介面地址 responseType: `arraybuffer` //一定要寫 }) .then(res => { if(res.status == 200){ let blob = new Blob([res.data], { type: `application/msword` //word文件為msword,pdf文件為pdf }); let objectUrl = URL.createObjectURL(blob); let link = document.createElement("a"); let fname = `我的文件`; //下載檔案的名字 link.href = objectUrl; link.setAttribute("download", fname); document.body.appendChild(link); link.click(); }else { this.$message({ type: "error", message: "匯出失敗" }) } })
後端返回的文件流的格式:
PDF格式:
word格式: