Dears, I have been struggling with uploading an image on a flask form in my application. I have simplified the code to just show if the form has picked up a file by a print statement. The script is as follows:
from flask import Flask, render_template, session, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import SubmitField
from flask_wtf.file import FileField
from PIL import Image
import os
from main import app
class Uploadform(FlaskForm):
picture = FileField('Update Profile Pic')
submit = SubmitField('Submit')
#### route
@app.route('/', methods=['GET', 'POST'])
def upload():
form = Uploadform()
path = app.root_path
if form.validate_on_submit:
print('form submitted')
if form.picture.data:
print('image available')
img = form.picture.data
print(img)
else:
print('no image')
return render_template ('form.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
HTML form goes a follows:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="POST" action="{{url_for('upload')}}">
{{ form.hidden_tag() }}
{{ form.csrf_token }}
{{form.picture.label}} <br>
{{form.picture}} <br>
{{form.submit() }} <br>
</form>
</body>
</html>
When I run the above I get the print statements: 'form submitted' and 'no image'
Many thanks for your help in advance.
CodePudding user response:
if form.validate_on_submit:
needs to be
if form.validate_on_submit():
CodePudding user response:
<form method="POST" action="{{url_for('upload')}}" enctype="multipart/form-data">
multipart/form-data
this value is necessary if the user will upload a file through the form.