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

时间:2016-02-26 10:52:23

标签: python flask

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

HTML CODE:

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

PYTHON CODE:

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)

但是它上传了一个文件而不是多个文件。

2 个答案:

答案 0 :(得分:10)

如何

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

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

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

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))
        # ...

您还可以使用此method生成随机文件名。

完整演示

查看:

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>

更多

为了获得更好的上传体验,您可以尝试Flask-Dropzone

答案 1 :(得分:2)

您的代码看起来很完美。 我认为你唯一的错误就是分裂并取得第一个价值。 而且我也不知道rsplit(),但split()对我来说非常适合。

HTML CODE


<input id="upload_img" name="zip_folder"  type="file" multiple  webkitdirectory  >

PYTHON CODE

@app.route('/zipped',methods = ['GET', 'POST'])
def zipped():
    if request.method == 'POST':
        f = request.files.getlist("zip_folder")
        print f
        for zipfile in f:
            filename = zipfile.filename.split('/')[1]
            print zipfile.filename.split('/')[1]
            zipfile.save(os.path.join(app.config['ZIPPED_FILE'], filename))
        return render_template('final.html')