• 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',
    });
  • 相关阅读:
    Cannot retrieve repository metadata (repomd.xml) for repository: fedora. P、、、
    Fedora 学习总结
    Gnome 高级配置
    [置顶]Fedora 13,14,15安装LAMP
    如何删去Fedora下应用程序菜单中的多余程序启动器?
    运用Telnet在windowsxp中与虚拟机中fedora14互联
    运用Telnet在Windows xp中与虚拟机中fedora14互连
    netstat 的应用
    在 fedora14 下升级 firefox 到 firefox4 的两种方案
    windows 中相关CMD应用
  • 原文地址:https://www.cnblogs.com/lutt/p/16171531.html
Copyright © 2020-2023  润新知