Uploading and Downloading Files in Flask

Uploading and Downloading Files in Flask

To handle uploading and downloading files in a Flask web application, you need to set up routes that can handle file uploads from users and serve files for users to download.

Here is a basic example that illustrates both of these processes:

Prerequisites:

Before you begin, ensure you have Flask installed. If you don't have Flask installed, you can install it using pip:

pip install Flask

Uploading Files

  • Set up the Flask app and a route to upload files:
import os
from flask import Flask, request, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'  # Replace with your desired upload directory
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        # If the user does not select a file, the browser submits an
        # empty file without a filename.
        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 '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
  • Serve the uploaded files:
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

Downloading Files

To allow users to download files, you can use the send_from_directory function that Flask provides:

@app.route('/download/<filename>')
def download_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)

The as_attachment=True parameter will prompt the browser to download the file rather than displaying it.

Running the Flask App

Don't forget to run the Flask app at the end of your script:

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

Notes:

  • The UPLOAD_FOLDER should be a directory on your server where uploaded files will be stored. This directory must be writable by the user that runs the Flask application.
  • The ALLOWED_EXTENSIONS set defines which file extensions are allowed to be uploaded. Adjust it according to your needs.
  • The secure_filename function from Werkzeug is used to sanitize the filename before storing it on the filesystem.
  • You might want to configure Flask to limit the size of uploads to prevent users from overwhelming your server with huge files.

Security Considerations:

When allowing file uploads, you should be very careful:

  • Never trust the filename provided by the client.
  • Always save files to a dedicated directory with restricted permissions.
  • Ensure uploaded files are not executable.
  • Validate the file type on both the client and server sides.
  • Consider scanning files for viruses and malware if they are to be served back to users or processed in any way.
  • Enforce size limits on uploaded files.

This example is very basic and serves to illustrate the concept. For a production environment, you'll need to handle exceptions, provide user feedback, and implement additional security measures.


More Tags

dalvik apache-spark-2.0 periodicity oauth-2.0 sum fuzzyjoin sharepoint windows-server-2008 breakpoints mpmovieplayercontroller

More Programming Guides

Other Guides

More Programming Examples