Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

python - 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'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...