-1
我想上傳多個圖像,但除了文件上的第一個圖像,所有其他圖像在上傳期間被損壞。我可以毫無問題地查看第一張圖片,但其他圖片無法查看。 windows說We can't open this file
。這幾乎聽起來像延伸是未知的。上傳多個圖像會破壞所有,但第一 - Flask
在附註中,當我查看其中一個損壞圖像的細節時,除底部以外的所有字段都是空的,文件名等。
# 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
的值在第一個圖像名稱後永不改變。所以顯然它沒有收到其他圖像的數據。
你遍歷文件,但你總是使用'form.photo.data'保存在最後。改用'image'。 – davidism
@davidism我不知道你在哪裏以及如何讓我使用'image'。 – Leustad
而不是'form.photo.data',就像該代碼塊的其他部分一樣。 – davidism