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! šÆ
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. š
To follow along, make sure you have Flask installed:
pip install flaskNow, let's create a new Flask application:
flask new upload_files_app
cd upload_files_appOpen the app.py file and let's define a route that handles file uploads:
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.
Now, let's create a route to display the uploaded files:
@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.
Create an index.html file in the static folder with the following content:
<!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.
Finally, let's run the application:
flask runNow, 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.
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! š”šā