get和post方式中“responseType”添加层级要注意,具体使用方法在下方
1、get方式下载
axios.get("/product/xxx", {
params: {
so: good_name.value,
},
responseType: "blob", // 注意这,一定要加,不然会出现文件损坏,打不开现象
})
.then(function (res) {
let contentDisposition = res.headers["content-disposition"]
let filename = decodeURI(contentDisposition.split("fileName=")[1] || contentDisposition.split("filename=")[1])
let blob = new Blob([res.data], { type: res.headers["content-type"] })
const url = window.URL.createObjectURL(blob)
const link = document.createElement("a")
link.href = url
link.download = filename
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(url) // 释放内存
document.body.removeChild(link)
})
.catch((err) => {})
2、post方式下载,此时responseType不能写在data参数对象中,要与data同级
axios.post("/product/xxx", { so: good_name.value }, {
responseType: "blob", // 注意这,一定要加,不然会出现文件损坏,打不开现象
})
.then(function (res) {
let contentDisposition = res.headers["content-disposition"]
let filename = decodeURI(contentDisposition.split("fileName=")[1] || contentDisposition.split("filename=")[1])
let blob = new Blob([res.data], { type: res.headers["content-type"] })
const url = window.URL.createObjectURL(blob)
const link = document.createElement("a")
link.href = url
link.download = filename
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(url) // 释放内存
document.body.removeChild(link)
})
.catch((err) => {})