Flask Tutorials: Saving Uploaded Files

beginner
23 min

Flask Tutorials: Saving Uploaded Files

Welcome back, aspiring developers! Today, we're going to dive into a fascinating aspect of Flask web development - saving uploaded files. This lesson is designed for both beginners and intermediates, so let's get started! šŸŽÆ

Understanding the Problem

In many web applications, users might need to upload files. For instance, a photo-sharing platform, a blog where users can upload images, or even a file-sharing service. Flask provides a simple and efficient way to handle file uploads. šŸ“

Setting Up the Environment

To follow along, make sure you have Flask installed:

bash
pip install flask

Now, let's create a new Flask application:

bash
flask new upload_files_app cd upload_files_app

Defining the Route for File Upload

Open the app.py file and let's define a route that handles file uploads:

python
from flask import Flask, request, send_from_directory, make_response app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads' @app.route('/upload', methods=['POST']) def upload_file(): if 'file' not in request.files: return "No file part" file = request.files['file'] if file.filename == '': return "No selected file" if file: file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) return f"File {file.filename} uploaded successfully"

šŸ“ Note that we've defined a route /upload for handling file uploads using the POST method. The uploaded file is saved in the uploads folder we defined in the configuration.

Displaying Uploaded Files

Now, let's create a route to display the uploaded files:

python
@app.route('/') def index(): return app.send_static_file('index.html') @app.route('/uploads/<filename>') def send_uploaded_file(filename): file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) if os.path.exists(file_path): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) return "File not found"

šŸ“ Note that we have an index.html file in the static folder, which we use as our main application page.

Creating the HTML Form

Create an index.html file in the static folder with the following content:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Upload Files</title> </head> <body> <h1>Upload a file:</h1> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> <h2>Uploaded Files:</h2> <ul id="files"> </ul> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ function loadFiles() { $.getJSON("/files", function(data){ $('#files').empty(); $.each(data, function(index, file){ $('#files').append('<li><a href="/uploads/' + file + '">' + file + '</a></li>'); }); }); } loadFiles(); setInterval(loadFiles, 5000); }); </script> </body> </html>

šŸ“ Note that we've created an HTML form for file uploads and a JavaScript function that updates the list of uploaded files every 5 seconds.

Running the Application

Finally, let's run the application:

bash
flask run

Now, open your browser and navigate to http://127.0.0.1:5000/. You'll see the file upload form, and you can test the functionality by uploading files.

Quiz

Quick Quiz
Question 1 of 1

Where are the uploaded files saved?

That's it for today! With this lesson, you've learned how to save uploaded files in Flask web applications. Keep exploring, keep learning, and happy coding! šŸ’”šŸ“āœ