Serving Uploaded Files with Flask: A Comprehensive Tutorial

beginner
11 min

Serving Uploaded Files with Flask: A Comprehensive Tutorial

Welcome to this beginner-friendly tutorial on serving uploaded files using Flask! By the end of this lesson, you'll be able to build web applications that can handle file uploads and serve them back to users. Let's dive in!

What is Flask?

šŸ“ Flask is a lightweight web framework for Python, perfect for beginners and small to medium-sized web applications. It's easy to set up, modular, and highly flexible.

Setting Up a Basic Flask Application

Before we get started, make sure you have Python and Flask installed on your computer. If you're unsure about this, follow our Flask Tutorial: Setting Up a Basic Flask Application.

Creating a File Upload Form

šŸŽÆ To allow users to upload files, we'll create a simple HTML form with an input field for file selection.

html
<form action="/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form>

Implementing File Upload Handling in Flask

Now let's see how to process the uploaded file and serve it back to the user in our Flask application.

Defining the Upload Route

In Flask, we define routes to handle specific URLs. For file uploads, we'll create a new route called /upload.

python
from flask import Flask, request, send_from_directory app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload_file(): # Process the uploaded file here return 'File uploaded successfully!'

Handling the Uploaded File

To access the uploaded file, we can use the request object's files dictionary. The key 'file' (the name of our file input field) corresponds to the uploaded file.

python
@app.route('/upload', methods=['POST']) def upload_file(): file = request.files['file'] # Save the file to a folder called 'uploads' file.save(os.path.join('uploads', file.filename)) return 'File uploaded successfully!'

šŸ’” Pro Tip: Save the uploaded files in a separate folder to keep your project organized.

Serving Uploaded Files with Flask

Now that we have saved the uploaded files, let's create a new route to serve them back to the user.

python
@app.route('/uploads/<path:filename>') def send_uploaded_file(filename): return send_from_directory('uploads', filename)

With this route in place, users can now access the uploaded files by navigating to the URL /uploads/<filename>.

Putting It All Together

Create a new file called app.py and paste the following code:

python
from flask import Flask, request, send_from_directory, render_template import os app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads' @app.route('/') def home(): return render_template('index.html') @app.route('/upload', methods=['POST']) def upload_file(): file = request.files['file'] if file.filename == '': return 'No file uploaded.' if file: file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) return 'File uploaded successfully!' @app.route('/uploads/<path:filename>') def send_uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) if __name__ == '__main__': app.run(debug=True)

Create a new folder called templates and inside it, create a new file called index.html. Paste the following HTML code:

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

Testing Your Application

Now that everything is set up, run your Flask application and navigate to http://127.0.0.1:5000/ in your web browser. You should see the file upload form. Upload a file, and you can access it at http://127.0.0.1:5000/uploads/<filename>.

Quiz

Quick Quiz
Question 1 of 1

Which Flask function is used to send a file from the server to the client?

And there you have it! You've learned how to serve uploaded files using Flask. This skill will be useful in building various web applications, such as file sharing systems or content management systems. Keep learning, and happy coding! šŸš€