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', });
python 中文名:蟒蛇,设计者:Guido van Rossum