Categories
Python Answers

How to upload image in Flask and Python?

Spread the love

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

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

How to upload image in Flask and Python?

To upload image in Flask and Python, we can get the uploaded file from the request.files property.

For instance, we write

import os
from flask import Flask, request

UPLOAD_FOLDER = "./upload"

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


@app.route("/", methods=["GET", "POST"])
def upload_file():
    if request.method == "POST":
        if "file1" not in request.files:
            return "there is no file1 in form!"
        file1 = request.files["file1"]
        path = os.path.join(app.config["UPLOAD_FOLDER"], file1.filename)
        file1.save(path)
        return "ok"
    return """
    <h1>Upload new File</h1>
    <form method="post" enctype="multipart/form-data">
      <input type="file" name="file1">
      <input type="submit">
    </form>
    """


if __name__ == "__main__":
    app.run()

to add the upload_file function that’s mapped to the / route.

In it, we check for the file uploaded with the request.files dictionary.

We check for the file with key file1 with "file1" not in request.files.

If it exists, then we get the file’s path with

os.path.join(app.config["UPLOAD_FOLDER"], file1.filename)

Then we save the file with file1.save(path).

If the request method isn’t 'POST', then we show use the file upload form to let them upload the file.

Conclusion

To upload image in Flask and Python, we can get the uploaded file from the request.files property.

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 *