一尘不染

如何在python中使用flask上传多个文件

flask

这是我上传多个文件的代码:

HTML代码:

Browse <input type="file" name="pro_attachment1" id="pro_attachment1" multiple>

密码:

pro_attachment = request.files.getlist('pro_attachment1')

for upload in pro_attachment:
    filename = upload.filename.rsplit("/")[0]
    destination = os.path.join(application.config['UPLOAD_FOLDER'], filename)
    print "Accept incoming file:", filename
    print "Save it to:", destination
    upload.save(destination)

但是它会上传单个文件,而不是多个文件。


阅读 711

收藏
2020-04-07

共1个答案

一尘不染

在模板中,你需要mulitple在上传输入中添加属性:

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="photos" multiple>
    <input type="submit" value="Submit">
</form>  

然后在查看功能中,上传的文件可以通过列表获取request.files.getlist('photos')。循环此列表并在每个项目(werkzeug.datastructures.FileStorage)上调用save()方法将它们保存在给定路径中:

import os

from flask import Flask, request, render_template, redirect

app = Flask(__name__)
app.config['UPLOAD_PATH'] = '/the/path/to/save'

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST' and 'photo' in request.files:
        for f in request.files.getlist('photo'):
            f.save(os.path.join(app.config['UPLOAD_PATH'], f.filename))
        return 'Upload completed.'
    return render_template('upload.html')

此外,你可能需要使用secure_filename()来清洁文件名:

# ...
from werkzeug.utils import secure_filename
# ...
    for f in request.files.getlist('photo'):
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        # ...

你也可以使用此方法生成随机文件名。

完整演示
视图:

import os

from flask import Flask, request, render_template
from werkzeug.utils import secure_filename

app = Flask(__name__)  
app.config['UPLOAD_PATH'] = '/the/path/to/save'

@main.route('/upload', methods=['GET', 'POST'])
def upload():
    form = UploadForm()
    if form.validate_on_submit() and 'photo' in request.files:
        for f in request.files.getlist('photo'):
            filename = secure_filename(f.filename)
            f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        return 'Upload completed.'
    return render_template('upload.html', form=form)

形成:

from flask_wtf import FlaskForm
from wtforms import SubmitField
from flask_wtf.file import FileField, FileAllowed, FileRequired

class UploadForm(FlaskForm):
    photo = FileField('Image', validators=[
        FileRequired(),
        FileAllowed(photos, 'Image only!')
    ])
    submit = SubmitField('Submit')

模板:

<form method="POST" enctype="multipart/form-data">
    {{ form.hidden_tag() }}
    {{ form.photo(multiple="multiple") }}
    {{ form.submit }}
</form>
2020-04-07