有没有办法用Flask接收多个上传的文件?我尝试了以下内容:
<form method="POST" enctype="multipart/form-data" action="/upload">
<input type="file" name="file[]" multiple="">
<input type="submit" value="add">
</form>
然后打印request.files['file']
:
@app.route('/upload', methods=['POST'])
def upload():
if not _upload_dir:
raise ValueError('Uploads are disabled.')
uploaded_file = flask.request.files['file']
print uploaded_file
media.add_for_upload(uploaded_file, _upload_dir)
return flask.redirect(flask.url_for('_main'))
如果我上传多个文件,它只打印集合中的第一个文件:
<FileStorage: u'test_file.mp3' ('audio/mp3')>
有没有办法使用Flask的内置上传处理接收多个文件?谢谢你的帮助!
答案 0 :(得分:75)
您可以使用getlist的方法flask.request.files,例如:
@app.route("/upload", methods=["POST"])
def upload():
uploaded_files = flask.request.files.getlist("file[]")
print uploaded_files
return ""
答案 1 :(得分:4)
使用Flask 1.0.2:
files = request.files.getlist("images")
images
是键/值对的键。值是多张图片。
答案 2 :(得分:2)
这是烧瓶版本1.0.2的有效解决方案:
images = request.files.to_dict() #convert multidict to dict
for image in images: #image will be the key
print(images[image]) #this line will print value for the image key
file_name = images[image].filename
images[image].save(some_destination)
基本上,images [image]带有添加了保存功能的图像文件 现在,您可以对数据做任何想做的事情。
答案 3 :(得分:0)
@app.route('/upload', methods=['GET','POST'])
def upload():
if flask.request.method == "POST":
files = flask.request.files.getlist("file")
for file in files:
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
对我有用。
对于UPLOAD_FOLDER,如果您需要在app = flask.Flask( name )
之后添加UPLOAD_FOLDER = 'static/upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER