vue+flask实现文件的下载

1、首先定义后端flask接口,将文件转换为二进制流

@app.route('/download', methods=['GET'])
def download():
    file = open("./upload/test.zip", "rb").read()
    response = make_response(file)
    return response

2、前端发送请求获取数据

(1)首先可以直接通过a标签发送请求如下,服务器运行在本地5000端口

<a href="http://localhost:5000/download">下载数据</a>

(2)也可以通过fetch和axios发送请求

fetch:因为fetch包裹了两层promise,第一层获取响应同时调用其blob方法将数据转为blob,第二层接收blob,并创建a标签实现下载
fetch('http://localhost:5000/download', {
  method: 'GET'
})
  .then((res) => {
    return res.blob()
  })
  .then(data => {
    const blobUrl = window.URL.createObjectURL(data)
    const a = document.createElement('a')
    a.style.display = 'none'
    a.download = 'test.zip'
    a.href = blobUrl
    a.click()
  })
axios由于vue项目用axios更多,也可以使用axios,注意get请求的config是第二个参数进行配置的,而post是第三个;并且这里需要配置responseType为blob
this.$https.get('/download', {
  responseType: 'blob'
}).then((res) => {
  const blobUrl = window.URL.createObjectURL(res.data)
  const a = document.createElement('a')
  a.style.display = 'none'
  a.download = 'test.zip'
  a.href = blobUrl
  a.click()
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值