How to Upload File in Python - Flask
0 1002
Introduction
Uploading files is a common requirement in web applications. With Python's Flask framework, handling file uploads becomes straightforward. This guide walks you through the steps to create a simple Flask app that accepts file uploads securely and efficiently.
Project Structure
To get started, set up your project folder with the following structure:
app.py– main Flask applicationtemplates/– contains your HTML filesuploads/– directory where uploaded files will be saved
Configuring Flask for File Upload
First, import the necessary modules and configure your app to specify the upload folder and allowed file types.
from flask import Flask, request, render_template, redirect, url_for
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # Max upload size: 16MB
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
Creating the Upload Route
The upload route handles both displaying the upload form and processing the uploaded file when the form is submitted.
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
if 'file' not in request.files:
return 'No file part in the request'
file = request.files['file']
if file.filename == '':
return 'No file selected for uploading'
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return f'File successfully uploaded: {filename}'
else:
return 'Allowed file types are txt, pdf, png, jpg, jpeg, gif'
return render_template('upload.html')
Upload Form Template
Create a simple HTML form to select and upload a file:
<!-- templates/upload.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload File</title>
</head>
<body>
<h1>Upload a File</h1>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>
</body>
</html>
Important Points to Remember
- Use
secure_filenamefrom Werkzeug to avoid unsafe filenames. - Check if the uploaded file has an allowed extension for security.
- Set a maximum upload size to prevent denial-of-service attacks.
- Always include
enctype="multipart/form-data"in your form for file uploads.
Running the Application
Run your Flask app with the following command:
if __name__ == '__main__':
app.run(debug=True)
Open http://127.0.0.1:5000/ in your browser, select a file, and hit upload to test the functionality.
Conclusion
Handling file uploads in Flask is simple and secure when you follow best practices like validating file extensions and sanitizing filenames. This tutorial provides a solid foundation to integrate file uploading features into your Python web apps using Flask.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments