Create a simple image upload site with Flask
In web applications, implementing image upload function is a common requirement. The Flask framework provides simple and flexible tools that make building such features relatively simple. This article will explain how to use the Flask framework to create a simple image upload site, as well as the key technologies and steps involved.
Flask is a lightweight Python web framework that is simple and easy to use and is suitable for rapid development of web applications. One of the common use cases is to create an image upload site that allows users to upload images and display them on web pages. This article will demonstrate how to implement such a simple image upload site using the Flask framework.
Install Flask: First make sure you have Python installed, and then you can install Flask using the pip tool. You can run it in the command line
pip install Flask
Come install Flask.Create Flask app: Create a Flask application in a Python script. You can import the Flask class and use it to create an application instance.
Set Upload Folder: Set up a folder in the application to store uploaded pictures. You can configure the application
UPLOAD_FOLDER
Variables to specify the saving path of the uploaded file.Allowed file types: Define a function to check whether the uploaded file type is within the allowed range. This can increase security and prevent users from uploading malicious files.
Create an upload page: Create a simple HTML page for uploading images. You can use forms to implement upload function and convert the form's
enctype
The property is set tomultipart/form-data
, to support file upload.Process file upload: Set up a route in the Flask application to handle file uploads. When a user submits a form, the Flask app receives the uploaded file and saves it to the specified folder.
Show upload results: Create another route to display the upload result. After the upload is successful, you can return a page or message to the user, telling them that the image has been uploaded successfully.
This is the basic step to creating a simple image upload site.
Step 1: Install Flask
First, make sure you have the Flask framework installed. You can use the pip command to install:
pip install Flask
Step 2: Create Flask Application
Next, we will create a Python file to define our Flask application. We call it. In this file, we will define the routing, process image uploads, and display uploaded images.
from flask import Flask, render_template, request, redirect, url_for, flash from import secure_filename import os UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} app = Flask(__name__) app.secret_key = "secret key" ['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and ('.', 1)[1].lower() in ALLOWED_EXTENSIONS @('/') def index(): return render_template('') @('/', methods=['POST']) def upload_file(): if 'file' not in : flash('No file part') return redirect() file = ['file'] if == '': flash('No image selected for uploading') return redirect() if file and allowed_file(): filename = secure_filename() ((['UPLOAD_FOLDER'], filename)) flash('Image successfully uploaded and displayed below') return render_template('', filename=filename) else: flash('Allowed image types are - png, jpg, jpeg, gif') return redirect() if __name__ == "__main__": (debug=True)
Step 3: Create HTML template
Flask uses the Jinja2 template engine to render dynamic content. We will create an HTML template named, used to display the image upload form and uploaded pictures.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Image Upload</title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} <h1>Upload an Image</h1> <form method="POST" enctype="multipart/form-data"> <input type="file" name="file" accept="image/*"> <input type="submit" value="Upload"> </form> {% if filename %} <h2>Uploaded Image:</h2> <img src="{{ url_for('static', filename='uploads/' + filename) }}" alt="Uploaded Image"> {% endif %} </body> </html>
Step 4: Run the application
After writing the code, we can run our Flask application. Just run in the terminaldocument:
python
Then, access in the browserhttp://127.0.0.1:5000/
, you can see the simple image upload site we created!
Advanced expansion
While we have created a simple image upload site, there are many features to add and improve. Here are some possible extensions and improvements:
User authentication and permission control: Add user authentication function so that only authorized users can upload images. You can use Flask-Login or Flask-Security to implement user authentication and permission control.
Image zoom and compression: Before uploading images, the images can be scaled and compressed to reduce file size and save storage space.
Image preview and editing: While uploading pictures, it provides a preview function, allowing users to view pictures and edit them, such as cropping, rotating and other operations.
Image storage optimization: Consider using cloud storage services such as Amazon S3 or Google Cloud Storage to store uploaded images for improved scalability and performance.
File management and cleaning: Regularly clean up uploaded images and delete images that have not been used for a long time to save storage space and keep the system clean.
Security enhancement: Ensure that necessary security measures are taken when handling file uploads to prevent malicious file uploads and file inclusion vulnerabilities.
We explain how to create a simple image upload site using the Flask framework and explore some possible extensions and improvements. Flask's flexibility and simplicity make it ideal for building a variety of web applications. Through continuous learning and exploration, you can further improve and customize your image upload site to meet various needs and user expectations.
Summarize
In this technical article, we explore how to create a simple image upload site using the Flask framework. We started by installing Flask and gradually introduced the key steps to creating a Flask application, including defining routes, handling image uploads, and rendering pages using HTML templates. We also discussed advanced expansion directions, such as user authentication, image processing, storage optimization, etc. Through this article, readers can learn how to build web applications using the Flask framework and learn how to perfect their projects through continuous improvement and expansion. Flask's simplicity and flexibility make it a powerful tool for developing web applications, and readers can further explore and apply this knowledge according to their needs and interests.
The above is the detailed process of using Flask to create a simple image upload site. For more information about Flask creating an upload site, please follow my other related articles!