上传文件使用 formData 格式来实现,而除去file文件,需要另外的参数时,也只需向 formData 中 append 数据就行:
let fd = new FormData()
fd.append('file', file)
fd.append('model', this.dataType)
this.$http({
url: 'xxxxxx',
method: 'post',
type: 'file',
data: fd,
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => {})
文件下载有多种方式,常见的就是直接给一个链接,指向服务器上的文件,前端页面用a标签点击下载就行;另一种方式是后端给下载接口,返回文件流,这种一般用于需要动态生成内容不确定的文件,实现步骤为:
1.调用接口
2.从接口 response headers 中获取到 content-disposition,从中分离出文件名
3.从 response 中得到要导出的文件类型 type 和文件流数据 data
4.结合上面得到的 data、type 生成 blob
5.生成一个 display:none 的 a 标签,标签 url 指向 blob
6.js 模拟点击,导出成功
7.移除 a 标签
this.$http({
url: 'xxxxxx',
method: 'post',
requestBody: {},
preHandle: request => {
request.responseType = 'blob'
}
}).then(res => {
let data = res.data
let type = res.data.type
let name = res.headers['content-disposition']?.split('=')[1]
let blob = new Blob([data], { type: type })
let a = document.createElement('a')
a.href = window.URL.createObjectURL(blob)
a.style.display = "none"
a.setAttribute("target", "_blank")
a.download = decodeURIComponent(name)
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
})