How to Upload an Image in Python
Introduction
In this tutorial I volition testify y'all how to upload image and brandish on the web page once information technology is uploaded successfully. I accept seen few tutorials on file uploads using Python Flask API but here I will bear witness y'all how to let users upload paradigm file and display it on the browser one time uploaded successfully.
Related Posts:
- Upload and display multiple images using Python and Flask
Prerequisites
Python 3.8.3 – 3.ix.1, Flask 1.1.2
Project Directory
Create a projection root directory calledpython-flask-upload-display-image as per your called location.
I may not mention the project's root directory name in the subsequent sections merely I will assume that I am creating files with respect to the project's root directory.
Configure Flask Application
I will configure application through flask framework. I will also ascertain our file upload location and maximum size of the file a user tin can upload.
You should not permit user to upload unlimited size of file due to security reasons or to avoid exhausting server space.
The standard directory for storing static resources such every bit images, css, javascript files into Flask awarding is to put under static directory. Here I am putting the uploaded file nether static/uploads directory from where finally yous will display the paradigm on the web page.
Create a file calledapp.py with the beneath code.
from flask import Flask UPLOAD_FOLDER = 'static/uploads/' app = Flask(__name__) app.secret_key = "hugger-mugger fundamental" app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
Configure Endpoint
Next I will create chief.py script to configure the endpoint for uploading file or image. It defines the required URIs for performing file upload operations.
I take immune sure types of images, such equally png, jpg, jpeg, gif.
I am using http method POST to upload the epitome file. After uploading and saving the prototype to disk I am returning the filename to the jinja2 flask template.
I have another function display_image()
that is used on the flask template to brandish the bodily image from the static/uploads
folder.
This below line is required when you want to serve the file or prototype from static folder but.
return redirect(url_for('static', filename='uploads/' + filename), code=301)
I take usedupload.html page for uploading file to the desired directory.
import os from app import app import urllib.request from flask import Flask, flash, request, redirect, url_for, render_template from werkzeug.utils import secure_filename ALLOWED_EXTENSIONS = ready(['png', 'jpg', 'jpeg', 'gif']) def allowed_file(filename): return '.' in filename and filename.rsplit('.', one)[ane].lower() in ALLOWED_EXTENSIONS @app.route('/') def upload_form(): return render_template('upload.html') @app.road('/', methods=['Mail']) def upload_image(): if 'file' not in request.files: wink('No file function') return redirect(request.url) file = request.files['file'] if file.filename == '': flash('No paradigm selected for uploading') return redirect(asking.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.salvage(os.path.join(app.config['UPLOAD_FOLDER'], filename)) #print('upload_image filename: ' + filename) wink('Prototype successfully uploaded and displayed below') return render_template('upload.html', filename=filename) else: flash('Allowed image types are -> png, jpg, jpeg, gif') return redirect(request.url) @app.route('/display/<filename>') def display_image(filename): #print('display_image filename: ' + filename) render redirect(url_for('static', filename='uploads/' + filename), code=301) if __name__ == "__main__": app.run()
View or Template File
Now you lot demand template folio for uploading file as well as it will too display the uploaded image. This isupload.html page kept nether directory –templates, which is the standard directory for storing template or view file in flask application.
<!doctype html> <title>Python Flask File Upload Case</title> <h2>Select a file to upload</h2> <p> {% with letters = get_flashed_messages() %} {% if messages %} <ul> {% for message in letters %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} </p> {% if filename %} <div> <img src="{{ url_for('display_image', filename=filename) }}"> </div> {% endif %} <course method="post" action="/" enctype="multipart/course-data"> <dl> <p> <input blazon="file" name="file" autocomplete="off" required> </p> </dl> <p> <input type="submit" value="Submit"> </p> </form>
Image used in this application for uploading and displaying:
Deploying the Application
Now navigate to the projection's root directory using control line tool and execute the controlpython main.py
or if your Python is on the classpath and so only execute master.py
, your server will be started on default port5000.
If you desire to change the port and so yous can alter the lineapp.run()
toapp.run(port=5001)
, where5001 is the new port.
Testing the Application
When yous hit the URL http://localhost:5000 in the browser to go the beneath folio to upload the image.
Once you lot select an image and upload then you will see the following screen:
Hope you got an thought how to upload and brandish image using Python Flask.
Download
Source: https://roytuts.com/upload-and-display-image-using-python-flask/
0 Response to "How to Upload an Image in Python"
Enregistrer un commentaire