- 需求:点击表格的某一行下载该行的文件,文件格式不确定
- 知识点:使用到
new Blob
;需要自己获取文件后缀,然后给文件的后缀格式设为变量,传给Blob - 逻辑:原来写下载都是固定下载…xlsx后缀的,这次没想到需要下载动态后缀的文件了,思维就是调取后端下载文件接口时,获取响应头下的数据
response.headers['content-disposition']
来看文件的格式后缀,截取最后的后缀传给下一步 - 代码环境:vue2、element
- 代码
export function downBinary(binary, config) {
const { fileName, contentType } = config
const eleLink = document.createElement('a')
eleLink.download = fileName || `${new Date().valueOf()}`
eleLink.style.display = 'none'
const blobConfig = {}
if (contentType) {
blobConfig.type = contentType
}
const blob = new Blob([binary], blobConfig)
eleLink.href = window.URL.createObjectURL(blob)
document.body.appendChild(eleLink)
eleLink.click()
document.body.removeChild(eleLink)
}
import { downBinary } from '@/utils/file'
async onDownLoad(row){
try{
this.fullScreenLoading = this.$loading({
lock: true,
text: '正在下载',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.5)'
})
let response = await commonDownLoad({xxx})
console.log(response,'response')
let lastindex = response.headers['content-disposition'].lastIndexOf('.')
let fileType = response.headers['content-disposition'].substring(lastindex+1)
let fileName = `${row.name}-${moment().format('YYYY年MM月DD日 HH时mm分ss秒')}.${fileType}`
const contentType = response.headers['content-type']
downBinary(response.data, { fileName, contentType })
}catch(err){
this.$message.error(err);
}finally{
this.fullScreenLoading.close()
}
}