2023.11.17使用flask将多个图片文件上传至服务器
2023.11.17使用flask将多个图片文件上传至服务器
实现功能: 1、同时上传多个图片文件 2、验证文件扩展名 3、显示上传文件的文件名 4、显示文件上传结果 程序结构 main.py
from flask import Flask, request, jsonify, render_template
import os
app = Flask(__name__)
# 设置上传文件存储目录
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# 允许上传的文件类型
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
@app.route('/')
def index():
return render_template('index.html')
# 检查文件名是否合法
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# 处理文件上传
@app.route('/upload', methods=['POST'])
def upload_file():
files = request.files.getlist("file")
success_files = []
failed_files = []
for file in files:
if file and allowed_file(file.filename):
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
success_files.append(filename)
else:
failed_files.append(file.filename)
if failed_files:
return jsonify({'message': '部分文件上传失败', 'failed_files': failed_files})
else:
return jsonify({'message': '所有文件上传成功', 'success_files': success_files})
if __name__ == '__main__':
app.run(debug=True)
index.html
文件上传