gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:36:57 29 4
gpt4 key购买 nike

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

HTML 代码:

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

Python 代码:

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)

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

最佳答案

如何

在模板中,需要在upload input中添加mulitple属性:

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

然后在 View 函数中,可以通过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 .

关于python - 如何在python中使用flask上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35649770/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com