Related Tutorial

10: Leveraging File Uploads in Your Flask Web Application

Leveraging File Uploads in Your Flask Web Application

Introduction:

In modern web applications, users often need to upload files for various purposes, ranging from images to documents. Integrating file uploads into your Flask web application can enhance its functionality and user experience. In this tutorial, we’ll explore how to implement file uploads in a Flask application, allowing users to upload files alongside their desired short names.

Example Code:

HTML Template (home.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</title>
</head>
<body>
    <h1>URL Shortener</h1>
    <form action="/" method="post" enctype="multipart/form-data">
        <label for="url">URL:</label><br>
        <input type="text" id="url" name="url"><br><br>
        <label for="short_name">Short Name:</label><br>
        <input type="text" id="short_name" name="short_name"><br><br>
        <input type="submit" value="Shorten">
    </form>

    <form action="/" method="post" enctype="multipart/form-data">
        <label for="file">File:</label><br>
        <input type="file" id="file" name="file"><br><br>
        <label for="short_name_file">Short Name:</label><br>
        <input type="text" id="short_name_file" name="short_name_file"><br><br>
        <input type="submit" value="Shorten">
    </form>
</body>
</html>

				
			

Python Script (app.py):

				
					from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def shorten_url():
    if request.method == 'POST':
        if 'url' in request.form.keys():
            # Code to handle URL submission
            pass
        else:
            # Code to handle file submission
            file = request.files['file']
            short_name = request.form['short_name_file']
            full_name = secure_filename(short_name + '_' + file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], full_name))
            # Update URLs.json with file information
            urls[short_name] = {'file': full_name}
    return render_template('home.html')

if __name__ == '__main__':
    app.run(debug=True)

				
			

Explanation:

In the HTML template, we’ve added a new form for file uploads alongside the existing form for URLs. The enctype="multipart/form-data" attribute is crucial for enabling file uploads in the form.

In the Python script, we’ve updated the route handler to distinguish between URL and file submissions based on the presence of the ‘url’ key in the form data. If a file is submitted, we extract the file and its associated short name, ensure the filename is secure using secure_filename, save the file to a designated upload folder, and update the urls dictionary with the file information.

Conclusion:

Integrating file uploads into your Flask web application can greatly enhance its functionality and user engagement. By following the steps outlined in this tutorial, you can seamlessly incorporate file upload capabilities into your Flask project, allowing users to upload files alongside their desired short names.