Vue-element-admin獲取ThinkPHP5 傳輸過來的excel資料流的發方法
阿新 • • 發佈:2018-11-04
api介面請求中新增responseType: 'arraybuffer',
export function exportData(data) {
return request({
url: '/crawler/taskmanagement/exportexcel',
responseType: 'arraybuffer',
method: 'post',
data
})
}
接受後端穿過來的資料流方法一:
DownloadData(id) { var that = this exportData({id: id}).then(res => { let blob = new Blob([res.data], {type: "application/vnd.ms-excel"}); let objectUrl = URL.createObjectURL(blob); window.location.href = objectUrl; }) },
接受後端穿過來的資料流方法二(此方法可以指定下載表格的名稱):
DownloadData(id) { var that = this exportData({id: id}).then(res => { const filename = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]) || '分揀表.xlsx' // 獲取後端返回存在請求頭裡邊的表單名字 that.$options.methods.fileDownload(res.data, filename); }) }, fileDownload(data, fileName) { const blob = new Blob([data], { type: 'application/octet-stream' }) const filename = fileName || 'filename.xls' if (typeof window.navigator.msSaveBlob !== 'undefined') { window.navigator.msSaveBlob(blob, filename) } else { var blobURL = window.URL.createObjectURL(blob) var tempLink = document.createElement('a') tempLink.style.display = 'none' tempLink.href = blobURL tempLink.setAttribute('download', filename) if (typeof tempLink.download === 'undefined') { tempLink.setAttribute('target', '_blank') } document.body.appendChild(tempLink) tempLink.click() document.body.removeChild(tempLink) window.URL.revokeObjectURL(blobURL) } },
後端使用ThinkPHP5,後端相關編碼請檢視https://blog.csdn.net/supramolecular/article/details/83303944