简洁明了,直接上代码吧
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)
更多请关注微信公众号
原文地址:https://www.cnblogs.com/nelson2013/p/9251944.html
时间: 2024-10-31 21:16:40