- I am trying to upload an image file to cloudinary which I have sent from my django template to a function in views.py
The file is in request.FILES['image']
cloudinary.config( cloud_name="p*****", api_key="33************", api_secret="4***-S***_o*********" ) img_obj = request.FILES['image'] cloudinary_response = cloudinary.uploader.upload(img_obj) image_url = cloudinary_response['url']
Printing img_obj gives the name of the image (Like : "tree.jpg")
cloudinary upload doc is as follows https://cloudinary.com/documentation/image_upload_api_reference#upload
The type of img_obj is InMemoryUploadedFile. Now is there a way to convert it to base64 or somthing like that so I can upload.
Or any other solution ??
Asked
Active
Viewed 3,624 times
0

Apon
- 152
- 1
- 3
- 12
-
Possible duplicate of [Encode Base64 Django ImageField Stream](https://stackoverflow.com/questions/36179539/encode-base64-django-imagefield-stream) – Clément Denoix Nov 23 '17 at 09:36
1 Answers
3
You have a few options:
img_obj.file
is the actual file object, so you could try uploading that directly.- Since an
InMemoryUploadedFile
is a subclass ofFile
, you can also justopen(mode='rb')
the file, using standard python file io functions. - Or you can try
img_obj.file.read()
I would go for the second option:
import base64
with img_obj.open("rb") as image_file:
encoded_string = base64.b64encode(image_file.read())

dirkgroten
- 20,112
- 2
- 29
- 42
-
This should solve the problem. But unfortunately doing this raise an exception __exit__ – Apon Nov 26 '17 at 04:06
-