Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save base64 image in django file field

I have following input

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA7YAAAISCAIAAAB3YsSDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAA5JxJREFUeNrsnQl4FEX6xqcJJEAS7ivhBkMAQTSJ4h0QEQ+I90rAc1cOL3QBXXV1AV1dVwmrsCqQ9VwJ6HoC7oon0T8iEkABwRC5IeE+kkAIkPT/nfmSmprunskk5CDw/p55hu7qOr76api8........" 

I want to save this file in file field. What can I do?

models.py

class SomeModel(models.Model):     file = models.FileField(upload_to=get_upload_report)     created = models.DateTimeField(auto_now_add=True)     modified = models.DateTimeField(auto_now=True) 

I'm trying to do this

def get_file(data):     from django.core.files import File     return File(data) 

and save return file to model instance

somemodel.file = get_file(image_base64_data) 

but it's gives a following error

AttributeError at /someurl/  'File' object has no attribute 'decode' 
like image 751
NIKHIL RANE Avatar asked Sep 19 '16 14:09

NIKHIL RANE


People also ask

How do I save an image in Base64 node?

To save a base64-encoded image to disk with Node. js, we can use the fs. writeFile method.

Can you Base64 encode an image?

With elmah. io's free image to Base64 encoder, it's easy to copy and paste markup or style for exactly your codebase. Simply drag and drop, upload, or provide an image URL in the controls above and the encoder will quickly generate a Base64 encoded version of that image.


1 Answers

import base64  from django.core.files.base import ContentFile format, imgstr = data.split(';base64,')  ext = format.split('/')[-1]   data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) # You can save this as file instance. 

Use this code snippet to decode the base64 string.

like image 197
Vaibhav Mule Avatar answered Oct 09 '22 03:10

Vaibhav Mule