Welcome back to CodeYourCraft! Today, we're diving into a practical and exciting topic - File Upload Configuration using Flask. Let's get started!
Flask is a micro web framework written in Python that makes it easy to build web applications. Today, we'll learn how to implement file uploads in a Flask application. This is a crucial skill for developing dynamic web applications that can handle user-generated content.
File uploads allow users to submit files as part of a form, which can be particularly useful for applications like image galleries, document management systems, and more. In this tutorial, we'll create a simple form for uploading files and learn how to handle those uploads in our Flask application.
Before we dive into the code, make sure you have the following prerequisites:
pip install flask)First, let's create a new directory for our application:
mkdir flask-file-upload
cd flask-file-uploadNext, we'll create a basic file structure for our application:
touch app.py
mkdir templates
touch templates/upload.html
touch requirements.txtNow, let's create an HTML template for our file upload form:
<!-- templates/upload.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<h1>Upload a file</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
</body>
</html>Next, we'll write the Flask application code that handles our form and processes the uploaded file:
# app.py
from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg'}
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOLDER'])
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
@app.route('/')
def upload_form():
return render_template('upload.html')
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=filename))
return redirect(request.url)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(debug=True)Now, let's run our application and test the file upload functionality:
python app.pyOpen your browser and navigate to http://127.0.0.1:5000/. You should see our file upload form. Try uploading a file to see the application in action!
Congratulations! You've successfully implemented file uploads in a Flask application. Now that you've seen how easy it is to handle user-generated content, take some time to experiment with this example and improve it based on your needs.
What is the purpose of the `UPLOAD_FOLDER` configuration in our Flask application?