FlaskFlask文件上传与下载

Posted nelson2013

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FlaskFlask文件上传与下载相关的知识,希望对你有一定的参考价值。

简洁明了,直接上代码吧

1. Flask实现文件上传

import os

from flask import jsonify
from flask import request


@app.route(‘/upload‘, methods=["POST"])
def upload_file():
    try:
        handle_upload()
    except Exception as e:
        return build_response(500, "Server error", None)
    return build_response(200, None, None)


def handle_upload():
    file = request.files[‘file‘]
    path = os.path.join("/Users/master/uploads", file.filename)
    file.save(path)


def build_response(code, msg, data):
    res = {
        "code": code
    }
    if code != 200:
        res["msg"] = msg
    else:
        res["data"] = data
    return jsonify(res)
    

2. Flask实现文件下载

# coding:utf-8
import os

from flask import jsonify
from flask import send_from_directory


@app.route(‘/download‘, methods=["POST"])
def download_report():
    try:

        dir_path = os.path.join("/Users/master", ‘uploads‘)
        file_name = "test.csv"
        return send_from_directory(dir_path, file_name, as_attachment=True)
    except Exception as e:
        return build_response(500, "Server error", None)
    return build_response(200, None, None)


def build_response(code, msg, data):
    res = {
        "code": code
    }
    if code != 200:
        res["msg"] = msg
    else:
        res["data"] = data
    return jsonify(res)

更多请关注微信公众号
技术分享图片


以上是关于FlaskFlask文件上传与下载的主要内容,如果未能解决你的问题,请参考以下文章

java Ftp上传创建多层文件的代码片段

性能工具之 JMeter 上传与下载脚本编写

文件的上传与下载

springboot项目关于文件的上传与下载

FlaskFlask与RESTful开发相关API

Android文件上传与下载