Fenil Shah
Fenil Shah

Reputation: 197

How can I upload or store images in a folder using Flask?

I currently have my images in a binary format along with the extension of the images. I would like to store images in a folder using flask. How can I do that?

Format of the image.

image = {
    'img_src': binary_format_of_image,
    'ext': image_extension,
    'id': image_id
}

Upvotes: 0

Views: 2872

Answers (1)

Patricio
Patricio

Reputation: 423

Flask has a intro into uploading files through your Flask Application

An approach from that page:

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

@app.route('/upload-my-image', methods=['POST'])
def upload_file():
   # check if the post request has the file part
   if 'file' not in request.files:
       flash('No file part')
       return redirect(request.url)
   file = request.files['file']
   # if user does not select file, browser also
   # submit an empty part without filename
   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(ABSOLUTE_PATH_TO_YOUR_FOLDER, filename))
       new_image = Image(
           path=PATH_TO_YOUR_FOLDER,
           filename=filename,
           ext=filename.rsplit('.', 1)[1].lower()
       )
       # Save new_image model
       return redirect(url_for('uploaded_file', filename=filename))

The datastructure that Flask request.files use is a FileStorage.

Also note that the <form> tag has to be marked with enctype=multipart/form-data and a <input type=file>

Upvotes: 2

Related Questions