0

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
}
Patricio
  • 403
  • 3
  • 10
Fenil Shah
  • 137
  • 1
  • 4
  • 10
  • You want to save every new image to be stored as a file in disk (inside a folder) or transform all your stored images to a file in disk? – Patricio May 29 '19 at 20:24
  • Store every new image as an image file in disk (inside a folder) – Fenil Shah May 29 '19 at 20:28
  • Possible duplicate of [Upload image in Flask](https://stackoverflow.com/q/44926465/608639), [Working with user uploaded image in Flask](https://stackoverflow.com/q/43309343/608639), [Flask image upload in HTML?](https://stackoverflow.com/q/31913257/608639), etc. – jww May 29 '19 at 21:44

1 Answers1

2

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>

Patricio
  • 403
  • 3
  • 10
  • I do not have a filename. I have the binary format of the image, so I don't think secure_filename would work. Is there a work around for images in binary format? – Fenil Shah May 29 '19 at 21:01
  • You want to receive as a binary format? you only need to save the binary file (`open(ABSOLUTE_PATH_FILENAME, 'wb') as file: file.write(data)` and assign a random filename – Patricio May 29 '19 at 21:15