上传多个图像会破坏除第一个Flas之外的所有内容

2024-06-20 15:01:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试上载多个图像,但除了文件中的第一个图像,所有其他图像都在上载过程中损坏。我可以看到第一个图像没有问题,但其余的不能看。windows显示We can't open this file。这听起来好像扩展是未知的。在

另一方面,当我查看其中一个损坏图像的详细信息时,所有字段都是空的,除了底部、文件名等。在

# view.py 
@myVacation_blueprint.route('/logVacation', methods=['GET', 'POST'])
@login_required
def log_vacation():
form = LogVacationForm()

if request.method == 'POST':
    if form.validate_on_submit():
        try:
            # Get the image name
            uploaded_images = request.files.getlist('photo')
            for image in uploaded_images:
                filename = secure_filename(image.filename)
                # Get the extension
                extension = filename.split('.')[1]
                filename = filename.split('.')[0]
                # Concatenate filename and current time
                filename = str(filename) + str(time.time())
                # Hash the filename
                hash_file_name = bcrypt.generate_password_hash(filename).decode('utf-8')
                # Normalize
                filename = "".join([c if c.isalnum() else "" for c in hash_file_name])
                # Add the extension
                filename = filename + '.' + str(extension)
                # Save the file
                directory = _user_img_folder(form)
                print(os.path.join(directory, filename))
                form.photo.data.save(os.path.join(directory, filename))
        except Exception as e:
            print(e)

        return render_template('myVacation.html')
    else:
        filename = None
return render_template('logVacation.html', form=form, error=error)


# forms.py
class LogVacationForm(FlaskForm):
vacation_name = StringField('Vacation Name', validators=[DataRequired(),   Length(min=6, max=25)])
location = StringField('Location', validators=[DataRequired()])
with_who = StringField('With_Who')
description = TextAreaField('Description', render_kw={
    'class': 'vacation_description',
    'rows': 10
})
photo = FileField('Select Images', validators=[
    # FileRequired(),
    FileAllowed(['jpg', 'png'], 'Images only')],
                  render_kw={'multiple': True}
                  )

# logVacation.html

# many lines....
<form class="logVacation" enctype=multipart/form-data role="form" method="post" action="/logVacation">
# Some other input
{{ form.photo(multiple="multiple") }}
# Some other input
<button class="btn btn-sm btn-success" value="upload" type="submit">Done</button>
</form>

我错过了什么?在

注意:我刚刚注意到在view.py处,form.photo.data的值在第一个图像名之后永远不会改变。所以很明显它没有收到其他图像的数据。在


Tags: thenamepy图像imageformifextension
1条回答
网友
1楼 · 发布于 2024-06-20 15:01:01
  • 如果使用form.validate_on_submit(),则可以删除{}。

  • .save()方法的对象是文件流(image),而不是表单数据(form.photo.data)。

就像这样:

if form.validate_on_submit():
    for image in request.files.getlist('photo'):
        ...
        image.save(os.path.join(directory, filename))

相关问题 更多 >