下面的url是请求后端接口,返回的是二进制流,通过Blob转为blob对象,然后通过a链接的download属性,进行下载:
this.$http({
url: url,
method: 'POST',
responseType: 'blob',
data: qs.stringify(data)
}).then(res => {
// console.log(res)
const link = document.createElement('a')
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
let num = ''
for (let i = 0; i < 4; i++) {
num += parseInt(Math.random() * 10)
}
var time = new Date()
var year = time.getFullYear()
var month =time.getMonth()+1 < 10 ? (0+""+(time.getMonth()+1)) : (time.getMonth()+1)
var day = time.getDate() < 10 ? (0+''+time.getDate()) : (time.getDate())
var dateTime = year + "" + month +""+ day
link.setAttribute('download', '访问日志_'+ dateTime +"_"+ num + '.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
this.$http({
url: url,
method: 'POST',
responseType: 'blob',
data: qs.stringify(data)
}).then(res => {
// console.log(res)
const link = document.createElement('a')
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) //此处写法为指定下载类型。如无指定类型下载,写法为 const blob = new Blob([res.data])
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
let num = ''
for (let i = 0; i < 4; i++) {
num += parseInt(Math.random() * 10)
}
var time = new Date()
var year = time.getFullYear()
var month =time.getMonth()+1 < 10 ? (0+""+(time.getMonth()+1)) : (time.getMonth()+1)
var day = time.getDate() < 10 ? (0+''+time.getDate()) : (time.getDate())
var dateTime = year + "" + month +""+ day
link.setAttribute('download', '访问日志_'+ dateTime +"_"+ num + '.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
可参考另外一种写法:
下面是上面转blob时,可能用到的格式:
后缀 | MIME Type |
---|---|
.doc | application/msword |
.docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.xls | application/vnd.ms-excel |
.xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.ppt | application/vnd.ms-powerpoint |
.pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
application/pdf |
格式参考:链接https://tool.oschina.net/commons/