flask实现一个文件下载功能

问题描述: 已知一个下载链接 download_url,直接下载下来的话,文件名是 xxx.xlsx, 根据产品要求,文件名必须是filename.xlsx.

解决问题:

方案1: 前端js去修改, 网上看了下, <a href="http://somehost/somefile.zip" download="filename.zip">Download file</a>

在html标签<a>加上download属性,但是好像并没有什么用,具体可以查看原文地址:

https://scarletsky.github.io/2016/07/03/download-file-using-javascript/

方案2: 后台先去下载保存在服务器,然后再下载给前端页面, 这样是可以,但是比较方案比较垃圾,下载时间翻倍,这里不做介绍

方案3: 使用python flask框架的stream流,相当于一个管道一样,将第三方地址的下载流转换到当前页面,下面是代码的实现

import requests

from flask import request, stream_with_context, Response

def file_downlad(url, file_name):

    # 首先定义一个生成器,每次读取512个字节

    def generate():

        r = requests.get(url, cookies=request.cookies, stream=True)

        for chunk in r.iter_content(chunk_size=512):

            if chunk:

                yield chunk

        response = Response(stream_with_context(generate()))

        content_disposition = "attachment; filename={}".format(file_name)

        response.headers['Content-Disposition'] = content_disposition

        return response

ps: 代码存手写,格式不对,拼写错误难免会发生

原文地址:https://www.cnblogs.com/weiguoyu/p/6393106.html