Categories
Python Answers

How to upload an image in Python Flask?

Spread the love

Sometimes, we want to upload an image in Python Flask.

In this article, we’ll look at how to upload an image in Python Flask.

How to upload an image in Python Flask?

To upload an image in Python Flask, we can get the uploaded file from request.files in our view.

For instance, we write

import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

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

def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']

        if file.filename == '':
            flash('No selected file')
            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))

to get the uploaded file from the form data entry with key file with

file = request.files['file']

We check if the file isn’t selected with

if file.filename == ''

Then we save the file to disk with

file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

Conclusion

To upload an image in Python Flask, we can get the uploaded file from request.files in our view.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *