Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - how to read request.files['image'] as base64?

I'm using Python Flask as my backend and faced a little problem. In the frontend application I have a form that contains an image upload feature.

In the backend I refer a variable to the image with image = request.files['image']

That exports a FileStorage object.

I want to convert the image to base64 format in order to insert it to my DB. I tried a lot of things but nothing worked. Anyone knows?

like image 348
GMe Avatar asked May 23 '17 19:05

GMe


People also ask

Is there a readable file stream in flask?

Flask already provides you with a readable file stream. PS: When choosing variable names, try to avoid built-in identifiers such as str. It can save you some trouble. Show activity on this post. When you open a file with a relative file path (i.e. simply passing Tulips.jpg) a path to a file is calculated relatively to the current working directory.

How to search for a file in flask?

You may also want to check out all available functions/classes of the module flask.request , or try the search function . def upload(): f = request.files['file'] assert f, "Where's my file?"

How to get the body of a POST request in flask?

When dealing with requests - the request module of flask allows you to represent incoming HTTP requests. A POST request's body can be extracted directly from the request itself and depending on the encoding - you'll access the appropriate field: request.json represents JSON sent as a request with the application/json content-type.

How do I download a CSV file in flask?

Go to browser and type “ http://localhost:8000/get-csv/<filename> ”, you can download the specified CSV File . . . , You can’t send all files into downloadable one.But if you convert all the files into ZIP and then you can send it as one file (zip file) 2. Create an Instance and Flask Routing


1 Answers

Basically you need to read it as a stream and then convert it to base64 format. Check the following answer:

Encoding an image file with base64

The solution shoud look like this:

import base64

...

image = request.files['image']  
image_string = base64.b64encode(image.read())
like image 173
Avi K. Avatar answered Oct 19 '22 19:10

Avi K.