I want to upload an image and pass it to the python code in flask so it can store and call the image locally. From a tutorial I have this code, however there seems to be a problem with the query, the request always ends with 'No file part':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
If I check which data is in the request:
print(request.data)
print(request.args)
print(request.form)
that gives me the following results:
b''
ImmutableMultiDict([])
ImmutableMultiDict([('file', '6b6e63084d829d765f318a123f9997d6.jpg')])
Here is my python code
ALLOWED_IMAGE_TYPES = set(["png", "jpg", "jpeg", "gif"])
def allowed_file(filename):
print("Check if image types is allowed")
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_IMAGE_TYPES
@app.route("/crop", methods=["GET", "POST"])
@login_required
def crop():
if request.method == "POST":
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No image selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
print("test2")
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
print('upload_image filename: ' filename)
flash('Image successfully uploaded and displayed below')
return render_template('index.html', filename=filename)
else:
flash('Allowed image types are - png, jpg, jpeg, gif')
return redirect(request.url)
else:
return render_template("crop.html")
@app.route('/display/<filename>')
def display_image(filename):
print('display_image filename: ' filename)
return redirect(url_for('static', filename='uploads/' filename), code=301)
<div >
<div >
<p>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</p>
{% if filename %}
<div>
<img src="{{ url_for('display_image', filename=filename) }}">
</div>
{% endif %}
<form method="POST" action="/crop" enctype="multipart/form-data">
<dl>
<p>
<input type="file" name="file" value="file" id="file" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" value="Submit" >
</p>
</form>
CodePudding user response:
request.files
is a dict object, so checking that the name is in it should work. For some reason it's not, so you could try checking if it's in keys()
instead, although that should be unnecessary.
if 'file' not in request.files.keys():
flash('No file part')
return redirect(request.url)