from flask import Flask,request,jsonify,send_from_directory
from werkzeug.utils import secure_filename
import os
#Flask 实现文件上传下载
app = Flask(__name__)
JSON_UPLOAD_FOLDER='json_upload'
RECORD_UPLOAD_FOLDER='record_upload'
app.config['JSON_UPLOAD_FOLDER'] = JSON_UPLOAD_FOLDER
app.config['RECORD_UPLOAD_FOLDER'] = RECORD_UPLOAD_FOLDER
ALLOWED_EXTENSIONS = set(['json','wav','mp3'])
basedir = os.path.abspath(os.path.dirname(__file__))
def allowed_file(filename):
return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS
def format_dir(filename):
# 不同类型文件路径不同
suffix = filename.rsplit('.', 1)[1]
if suffix == 'json':
file_dir = os.path.join(basedir, app.config['JSON_UPLOAD_FOLDER'])
elif suffix == 'mp3' or 'wav':
file_dir = os.path.join(basedir, app.config['RECORD_UPLOAD_FOLDER'])
return file_dir
# strict_slashes=None, 对URL最后的 / 符号是否严格要求
# 如:
# @app.route('/index',strict_slashes=False),
# 访问 http://www.xx.com/index/ 或 http://www.xx.com/index均可
# @app.route('/index',strict_slashes=True)
# 仅访问 http://www.xx.com/index
@app.route('/upload',methods=['POST'],strict_slashes=False)
def upload():
if request.method == 'POST':
upload_files = request.files['file']
filename = upload_files.filename
if upload_files and allowed_file(filename):
file_dir = format_dir(filename) # 获取文件保存路径
if not os.path.exists(file_dir):
os.makedirs(file_dir)
file_name = secure_filename(upload_files.filename)
upload_files.save(os.path.join(file_dir, file_name))
return jsonify({"errno": 0, "msg": "succeed "})
return jsonify({"errno": 1, "msg": "file suffix not allowed "})
@app.route("/download/<path:filename>",methods=['GET']) # filename是一个相对路径,相对于程序所在路径
def downloader(filename):
return send_from_directory(app.root_path, filename, as_attachment=True) # as_attachment=True 一定要写,不然会变成打开,而不是下载
if __name__ == '__main__':
app.run('0.0.0.0',8888,debug=True)
postman 测试结果: