上传文件携带额外参数+文件流生成实现下载

上传文件使用 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)
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值