Related Tutorial

11: How to Implement File Uploads in a Flask Web Application

Introduction:

In web development, allowing users to upload files is a common requirement. Whether it’s images, documents, or any other type of file, providing a seamless upload experience enhances user interaction. In this tutorial, we’ll walk through the process of implementing file uploads in a Flask web application.

Setting Up the Environment:

Before diving into the implementation, ensure you have Flask installed. If not, you can install it via pip:

				
					pip install Flask

				
			

Creating the Flask Application:

Let’s start by creating a Flask application. We’ll set up a basic structure with a home page where users can upload files.

				
					from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

if __name__ == '__main__':
    app.run(debug=True)

				
			

HTML Template for Home Page (home.html):

Now, let’s create a simple HTML template for our home page where users can upload files.

				
					<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="text" name="short_name" placeholder="Short Name">
<button type="submit">Upload</button>
</form>
</body>
</html>

				
			

Processing File Uploads in Flask:

Now, let’s handle the file upload functionality in our Flask application.

				
					from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        file = request.files['file']
        short_name = request.form['short_name']
        file.save(f'uploads/{short_name}_{file.filename}')
        return 'File uploaded successfully!'
    return render_template('home.html')

if __name__ == '__main__':
    app.run(debug=True)

				
			

Explanation:

  1. We’ve added a POST method to the route ‘/’ to handle form submissions.
  2. Inside the POST method, we retrieve the uploaded file using request.files['file'].
  3. We also retrieve the short name entered by the user using request.form['short_name'].
  4. The uploaded file is then saved to the ‘uploads’ directory with a combination of the short name and the original filename to prevent overwriting.
  5. Finally, a success message is returned to the user.

Conclusion:

Implementing file uploads in a Flask web application is straightforward. By following this tutorial, you can seamlessly integrate file upload functionality into your projects, enhancing user experience and interaction.

Remember to handle file validation and security measures to ensure the safety of your application and its users’ data. Happy coding!