後端:Java
前端:vue+element+axios
後端介面返回檔案流,前端呼叫實現前端匯出功能
export function websiteStatementDownloadApi(data) {
return request({
url: websiteStatementDownloadUrl,
method: 'post',
data,
responseType: "blob"
})
}
service.interceptors.response.use(
response => {
const res = response.data
if (response.headers['content-type'] === 'application/octet-stream;charset=utf-8') {
return response
}
// ......其他
const isBlob = response.config.responseType === 'blob'
if (!isBlob) {
Message({
message: (res.msg || 'Error'),
type: 'error',
duration: 5 * 1000
})
}
}
),
<el-button @click="fetchWebsiteStatementDownload">匯出</el-button>
import { websiteStatementDownloadApi} from '@/api/home'
import moment from 'moment'
export default {
data(){
return{
selectedDate: {
startDate: moment(new Date().getTime() - 3600 * 1000 * 24 * 7).format('yyyy-MM-DD'),
endDate: moment().format('yyyy-MM-DD')
}
}
},
methods:{
fetchWebsiteStatementDownload() {
websiteStatementDownloadApi(this.selectedDate).then(res => {
if (res.status === 200) {
const blob = new Blob([res.data], {
type: 'application/octet-stream',
})
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = (e) => {
const link = document.createElement('a');
link.download = `${this.selectedDate.startDate}to${this.selectedDate.endDate}.csv`;
link.href = e.target.result;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
this.$message.success('下載成功')
}
}
}).catch(e => console.log(e, 'error'))
},
}
}
Headers裡的返回值
列印出來的引數
後端介面已返回檔名在headers的 "content-disposition"裡,但列印出來只有content-length和content-type,就只好用請求引數拼了一樣格式的名字代替了。
小朋友,是不是有好多問號???