Flask框架编写文件下载接口过程讲解

2023-01-04 09:57:13
目录
方式一方式二完整代码

方式一

@app.route("/download1")
def download():
    # return send_file('test.exe', as_attachment=True)
    return send_file('2.jpg')
    # return send_file('1.mp3')

如果不加as_attachment参数,则会向浏览器发送文件,比如发送一张图片:

发送mp3

加上as_attachment参数,则会下载文件。

方式二

通过Response来实现

部分代码如下:

@app.route("/download2")
def download2():
    file_name = "1.jpg"
    #https://www.runoob.com/http/http-content-type.html
    response = Response(file_send(file_name), content_type='image/jpeg')
    response.headers["Content-disposition"] = f'attachment; filename={file_name}'
    return response

其中content-type要根据文件的具体类型来设置,具体参考如下常见的:

content-type(内容类型),一般是指网页中存在的 content-type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件,content-type 标头告诉客户端实际返回的内容的内容类型。

常见的媒体格式类型如下:

    text/html : HTML格式text/plain :纯文本格式text/xml : XML格式image/gif :gif图片格式image/jpeg :jpg图片格式image/png:png图片格式application/xhtml+xml :XHTML格式application/xml: XML数据格式application/atom+xml :Atom XML聚合格式application/json: JSON数据格式application/pdf:pdf格式application/msword : Word文档格式application/octet-stream : 二进制流数据(如常见的文件下载)application/x-www-form-urlencoded : 中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

    完整代码

    app.py

    from flask import Flask,send_file,Response
    from flask_cors import CORS
    app = Flask(__name__)
    CORS(app,resources={r"/*": {"origins": "*"}},supports_credentials=True)
    @app.route("/download1")
    def download():
        # return send_file('test.exe', as_attachment=True)
        # return send_file('2.jpg')
        return send_file('1.mp3')
        # filefold file
        # return send_from_directory('./', 'test.exe', as_attachment=True)
    # send big file
    def file_send(file_path): 
        with open(file_path, 'rb') as f:
            while 1:
                data = f.read(20 * 1024 * 1024)  # per 20M
                if not data:
                    break
                yield data
    @app.route("/download2")
    def download2():
        file_name = "1.jpg"
        response = Response(file_send(file_name), content_type='image/jpeg')
        response.headers["Content-disposition"] = f'attachment; filename={file_name}'
        return response
    if __name__ == '__main__':
        app.config['JSON_AS_ASCII'] = False
        app.run(debug=True)
    

    到此这篇关于Flask框架编写文件下载接口过程讲解的文章就介绍到这了,更多相关Flask文件下载内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!