- Python使用Flask框架同时上传多个文件的方法
- 简介
- 提炼代码
- 源代码
flask官方上传文档介绍
secure_filename方法的好处
提炼代码#!/usr/bin/python
# -*- coding: UTF-8 -*-
# *************************************
# Author: jenrey
# Time: 2021-11-08 16:04
# Desc: flask_upload.py
# *************************************
import os
from flask import Flask, request
from werkzeug.utils import secure_filename # http://docs.jinkan.org/docs/flask/patterns/fileuploads.html
app = Flask(__name__)
"""
http://docs.jinkan.org/docs/flask/patterns/fileuploads.html
"""
# app.config内的配置名均为固定搭配
# 储存上传的文件的地方
app.config['UPLOAD_FOLDER'] = 'uploads/'
# 允许的文件类型的集合
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'sh'])
# 上传文件限制为最大 16MB,如果请求传输一个更大的文件, Flask 会抛出一个 RequestEntityTooLarge 异常。
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
def allowed_file(filename):
"""
判断传入的文件后缀是否合规。不合规返回False
:param filename:
:return: True or False
"""
return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
@app.route('/upload', methods=['POST'])
def upload():
# postman:POST -> Body -> form-data -> KEY=file[]
uploaded_files = request.files.getlist("file[]")
filenames = []
error_filenames = []
for file in uploaded_files:
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
filenames.append(filename)
else: # 文件后缀不符合类型或者文件太大
error_filenames.append(file.filename)
if error_filenames: # 有文件上传失败的情况
result = {
'code': 200,
'result': 'failure',
'message': ",".join(error_filenames)
}
return result
else:
result = {
'code': 200,
'result': 'success',
'message': ''
}
return result
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=int("8091"),
debug=True
)
源代码
https://www.jb51.net/article/62606.htm
https://getbootstrap.com/docs/4.0/getting-started/download/
import os
# We'll render HTML templates and access data sent by POST
# using the request object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# and send_from_directory will help us to send/show on the
# browser the file that the user just uploaded
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename
# Initialize the Flask application
app = Flask(__name__)
# This is the path to the upload directory
app.config['UPLOAD_FOLDER'] = 'uploads/'
# These are the extension that we are accepting to be uploaded
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
return '.' in filename and
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
# This route will show a form to perform an AJAX request
# jQuery is loaded to execute the request and update the
# value of the operation
@app.route('/')
def index():
return render_template('index.html')
# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
# Get the name of the uploaded files
uploaded_files = request.files.getlist("file[]")
filenames = []
for file in uploaded_files:
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to the upload
# folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
# Save the filename into a list, we'll use it later
filenames.append(filename)
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
# Load an html page with a link to each uploaded file
return render_template('upload.html', filenames=filenames)
# This route is expecting a parameter containing the name
# of a file. Then it will locate that file on the upload
# directory and show it on the browser, so if the user uploads
# an image, that image is going to be show after the upload
@app.route('/uploads/')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=int("80"),
debug=True
)
index.html代码
How To Upload a File.
upload.html页面:
Uploaded files
This is a list of the files you just uploaded, click on them to load/download them{% for file in filenames %}
- {{file}}
{% endfor %}Code to manage a Upload
@app.route('/upload', methods=['POST']) def upload(): # Get the name of the uploaded file #file = request.files['file'] uploaded_files = request.files.getlist("file[]") filenames = [] for file in uploaded_files: # Check if the file is one of the allowed types/extensions if file and allowed_file(file.filename): # Make the filename safe, remove unsupported chars filename = secure_filename(file.filename) # Move the file form the temporal folder to the upload # folder we setup file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) filenames.append(filename) # Redirect the user to the uploaded_file route, which # will basicaly show on the browser the uploaded file # Load an html page with a link to each uploaded file return render_template('upload.html', filenames=filenames)



