I am creating user accounts using prebase auth.create_user_with_email_and_password
. Then I am storing the users' data in firebase realtime database. db.child("users").push("data")
where data= {"name": name, "email" : email, "password": password, "picture": picture}.
here picture is; picture = request.files['file']
But I am not able to send picture alongwith other data of user, image can not be sent in json object.
How can we upload picture, there are some solutions to upload image data but I want to send it alngwith other data so it may get stored with the other attributes of user data.

- 828
- 2
- 6
- 18
1 Answers
I would suggest two approches you could use:
Solution 1:
You could store your images in file system in any directory (i.e img_dir) and renaming it to ensure the name is unique. (i usually use a timestamp prefix) (myimage_20210101.jpg
).Now you can store this name in a DataBase. Then, while generating the JSON, you pull this filename ,generating a complete URL (http://myurl.com/img_dir/myimage_20210101.jpg) and then you can insert it into the JSON.
Solution 2:
Encode the image with Base 64 Encoding
and decode it while fetching.
Remember to convert to string first by calling .decode(), since you can't JSON-serialize a bytes without knowing its encoding.
That's because base64.b64encode
returns bytes, not strings.
import base64
encoded_= base64.b64encode(img_file.read()).decode('utf-8')
How to save an encoded64 image?
my_picture= 'data:image/jpeg;base64,/9j/4AAQSkZJRgAB............'
You'll need to decode the picture from base64 first, and then save it to a file:
import base64
# Separate the metadata from the image data
head, data = my_picture.split(',', 1)
# Decode the image data
plain_image = base64.b64decode(data)
# Write the image to a file
with open('image.jpg', 'wb') as f:
f.write(plain_image)

- 1,708
- 1
- 11
- 14
-
I am getting `TypeError: Object of type bytes is not JSON serializable` error while encoding image as `file = base64.b64encode(picture.read()) data = {"name": name, "email" : email, "password": password, "picture": file}` . Am I doing something wrong? – doc Aug 13 '21 at 06:40
-
try `file = base64.b64encode(YourPicture).decode()` – BlackMath Aug 13 '21 at 06:55
-
Yeah its working What e will do for downloading that file? – doc Aug 13 '21 at 07:35