vue 把 java 傳過來的流檔案 轉成apk、xls等
阿新 • • 發佈:2020-07-31
1、在請求頭設定:
export function downLoad(data) { return request({ url: '/app/downLoad', method: 'post', responseType: 'blob', //最關鍵的部分 headers: { 'Content-Type': 'application/json' }, data }) }
2、介面返回:
3、處理流檔案
downLoad({ type: e }).then(res => { console.log(res);let data = res; const that = this; let fileReader = new FileReader(); fileReader.onload = function() { try { // console.log(res); let jsonData = JSON.parse(this.result); if (jsonData.code) { that.$message({ message: jsonData.message, type:'error' }) // 說明是普通物件資料,後臺轉換失敗 } } catch (err) { // console.log(res); // 解析成物件失敗,說明是正常的流檔案,轉成 blob const blob = new Blob([res]);
// 設定下載的檔名 const fileName = '__UNI__' + formatDate(new Date(), 'yyyyMMddhhmmss') + '.apk'; //此次為檔名('__UNI__' + 當前時間 + .apk),若要 apk 轉成 excel 或其他檔案,設定檔案字尾為 .xlsx 等 即可 // 建立 a 標籤
const elink = document.createElement('a');
// 新增 a 標籤屬性 elink.download = fileName; elink.style.display = 'none'; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); // 下載 URL.revokeObjectURL(elink.href); // 釋放URL 物件 document.body.removeChild(elink); // 釋放 a 標籤 } }; fileReader.readAsText(data); }).catch(() => { that.loading = false })
4、示例: