小陆同学

python 中文名:蟒蛇,设计者:Guido van Rossum

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

flask+vue--下载文件

后端:

复制代码

from flask import Response

def
download_file(): file_name = 'aaaa.tar.gz' def send_chunk(): # 流式读取 store_path = '/data/aaaa.tar.gz' with open(store_path, 'rb') as target_file: while True: chunk = target_file.read(20 * 1024 * 1024) # 每次读取20M if not chunk: break yield chunk response = Response(send_chunk(), content_type='application/octet-stream') response.headers["access-control-expose-headers"] = "Content-disposition" # 必须加这个属性,才能在headers里成功添加Content-Disposition的配置 response.headers["Content-Disposition"] = 'attachment; filename=%s' % file_name return response
复制代码

前端:

<el-button type="text" @click="download_file(scope.row.id)">{{scope.row.backup_file}}</el-button>-->
复制代码
##我的axios请求进行了封装,因下载文件的responseType参数与其他不同,所以又封装了一个下载文件的axios实例
import  download_instance from '../../api/axiosinstance' 

   download_file(id){
      download_instance({
        method: 'post',
        url: '/api/app/download_file/',
        responseType: 'blob',
        data: {
          id: id
        }
      }).then(response => {
        const blob = new Blob([response.data], {type: 'application/tar.gz'});
        const filename = response.headers['content-disposition'];
        const downloadElement = document.createElement('a');
        const href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        [downloadElement.download] = [filename.split('=')[1]];
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放blob对
      }).catch((error) => {
        console.log(error)
      })

    },
复制代码

axiosinstance.js

复制代码
import Axios from 'axios'
import { Toast } from 'vant';
import URLS from '../../config/urls'

import router from '@/router'
//1、使用自定义配置新建一个 axios 实例
const instance = Axios.create({
    baseURL: URLS.API_URL,
    responseType: 'json',
});
//2、新建一个axios实例,用来下载文件
const download_instance = Axios.create({
    baseURL: URLS.API_URL,
    responseType: 'blob',
});
复制代码

 

posted on   小陆同学  阅读(509)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示