如何在python中使用瓶子上传多个文件 [英] how to upload multiple files using flask in python
问题描述
浏览< input type =filename =pro_attachment1id =pro_attachment1multiple>
PYTHON CODE:
pro_attachment = request.files.getlist('pro_attachment1')
在pro_attachment中上传:
filename = upload.filename.rsplit /)[0]
destination = os.path.join(application.config ['UPLOAD_FOLDER'],filename)
打印接受传入文件:,文件名
打印保存它到:,目标
upload.save(目的地)
但它上传一个单文件而不是多个文件。
如何
模板,您需要在上传输入中添加 mulitple
属性:
< ; form method =POSTenctype =multipart / form-data>
< input type =filename =photosmultiple>
< input type =submitvalue =Submit>
< / form>
然后在view函数中,上传的文件可以通过请求.files.getlist( '照片')
。循环播放列表并调用 save()方法在每个项目上( werkzeug.datastructures.FileStorage )将保存在给定的路径:
import os
$ b $ from flask flask Flask,request,render_template,redirect
$ b app = Flask(__ name__)
app.config ['UPLOAD_PATH'] ='\static\uploads'
@ app.route('/上传',方法= ['GET','POST'])
def upload():$ b $如果request.method =='POST'和'photo'request.files:
for f in request.files.getlist('photo'):
f.save(os.path.join(app.config ['UPLOAD_PATH'],f.filename))
return'Upload completed '
返回render_template('upload.html')
此外,您可能需要使用 secure_filename()到 clean 文件名:
<$ c $从$ werkzeug.utils导入secure_filename
$ ...
for $ request.files.getlist('photo'):
filename = secure_filename f.filename)
f.save(os.path.join(app.config ['UPLOAD_PATH'],filename))
#...
您也可以用这个方法
完整演示
查看:
进口os
$ b $从瓶子进口Flask,request,render_template __name__)
app.config ['UPLOAD_PATH'] ='\static\uploads'
@ main.route('/ upload',方法= ['GET','POST'])
def upload():
form = UploadForm()
如果request.files中的form.validate_on_submit()和'photo' b.files.getlist('photo'):
filename = secure_filename(f.filename)
f.save(os.path.join(app.config ['UPLOAD_PATH' ],文件名))
return'Upload completed。'
return render_template('upload.html',form = form)
$ b $ p
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' b $ b from flask_wtf.file import FileField,FileAllowed,FileRequired
$ b $ class UploadForm(FlaskForm):
photo = FileField('Image',validators = [
FileRequired(),
FileAllowed(照片,仅限图片!)
])
submit = SubmitField('Submit')
Template:
< form method =POSTenctype =multipar吨/格式数据>
{{form.hidden_tag()}}
{{form.photo(multiple =multiple)}}
{{form.submit}}
< / form> ;
更多
为了获得更好的上传体验,你可以尝试 Flask-Dropzone 。
Here is my code for multiple files upload:
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)
But it uploads a single file instead of multiple files.
How to
In the template, you need to add mulitple
attribute in upload input:
<form method="POST" enctype="multipart/form-data">
<input type="file" name="photos" multiple>
<input type="submit" value="Submit">
</form>
Then in view function, the uploaded files can get as a list through request.files.getlist('photos')
. Loop this list and call save() method on each item (werkzeug.datastructures.FileStorage) will save them at given path:
import os
from flask import Flask, request, render_template, redirect
app = Flask(__name__)
app.config['UPLOAD_PATH'] = '\static\uploads'
@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')
Furthermore, you may need to use secure_filename() to clean 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))
# ...
You can also generate a random filename with this method.
Full demo
View:
import os
from flask import Flask, request, render_template
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['UPLOAD_PATH'] = '\static\uploads'
@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)
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')
Template:
<form method="POST" enctype="multipart/form-data">
{{ form.hidden_tag() }}
{{ form.photo(multiple="multiple") }}
{{ form.submit }}
</form>
More
For better upload experience, you can try Flask-Dropzone.
这篇关于如何在python中使用瓶子上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!