通过blob下载后端传过来的文件
请求里面设置如下
export function download(data) {
return axios.get('/api/release/download', { params: data, responseType: 'blob' })
}
页面使用如下
// 下载
doDownLoad(row) {
this.downloadLoading = true
this.$notify.info({
message: 'File is downloading...',
duration: 2000
});
download({ id: row.id }).then(res => {
this.downloadF(res, row)
})
},
downloadF(res, row) {
const blob = row.type === '' ? new Blob([res], { type: 'application/octet-stream' }) : new Blob([res])
const url = window.URL.createObjectURL(blob)
let dom = document.createElement('a')
dom.style.display = 'none'
dom.href = url
dom.setAttribute('download', row.type === '' ? `${row.fileName}-${row.version}` : `${row.fileName}-${row.version}.${row.type}`)
document.body.appendChild(dom)
dom.click()
this.downloadLoading = false
}
需要注意的是当new Blob
里面不添加type
且dom.setAttribute('download', '文件名')
后面的文件名不设置格式的话 默认下载的格式为.txt
这个对于二进制文件是不想被看到的 所以需要对type进行处理
const blob = row.type === '' ? new Blob([res], { type: 'application/octet-stream' }) : new Blob([res])
点击下载的时候,当服务端返回过来的type为空的时候,此时这个文件就是二进制文件 需要对blob中的type进行设置type: 'application/octet-stream'
此时的文件名和文件类型都由前端进行定义
row.type === '' ? `${row.fileName}-${row.version}` : `${row.fileName}-${row.version}.${row.type}`