vue下载文件(下载文件服务器文件,并修改文件名和解决跨域问题)
文件在前端本地
var a = document.createElement('a')
a.setAttribute('href', "../xx.text")
a.setAttribute('download', "xx.text")
document.body.appendChild(a)
a.click()
文件存在文件服务器
<el-button size="small" type="primary" @click="down">下载 </el-button>
proxy: {
"/api": {
target: "https://gwt.xjbtylbz.cn:20002/",
changeOrigin: true,
pathRewrite: {
"^/api": ""
}
},
}
import axios from 'axios'
data() {
return {
url: '/api/ADMIN_ydGI6CuAknIQGM1648866955877.docx'
}
},
methods:{
down() {
const link = document.createElement('a')
axios .get(this.url, { responseType: 'blob',}).then((res) => {
const blob = new Blob([res.data], {
type: 'application/vnd.ms-excel'
})
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, "xx.docx")
} else {
const href = URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.href = href
a.download = "xx.docx"
a.click()
URL.revokeObjectURL(a.href)
}
})
}
}
|