Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Base64 file handling for django-tastypie
import base64
import os
from tastypie.fields import FileField
from django.core.files.uploadedfile import SimpleUploadedFile
class Base64FileField(FileField):
"""
A django-tastypie field for handling file-uploads through raw post data.
It uses base64 for en-/decoding the contents of the file.
Usage:
class MyResource(ModelResource):
file_field = Base64FileField("file_field")
class Meta:
queryset = ModelWithFileField.objects.all()
In the case of multipart for submission, it would also pass the filename.
By using a raw post data stream, we have to pass the filename within our
file_field structure:
file_field = {
"name": "myfile.png",
"file": "longbas64encodedstring",
"content_type": "image/png" # on hydrate optional
}
"""
def dehydrate(self, bundle):
if not bundle.data.has_key(self.instance_name) and hasattr(bundle.obj, self.instance_name):
file_field = getattr(bundle.obj, self.instance_name)
if file_field:
try:
content_type, encoding = mimetypes.guess_type(file_field.file.name)
b64 = open(file_field.file.name, "rb").read().encode("base64")
ret = {
"name": os.path.basename(file_field.file.name),
"file": b64,
"content-type": content_type or "application/octet-stream"
}
return ret
except:
pass
return None
def hydrate(self, obj):
value = super(FileField, self).hydrate(obj)
if value:
value = SimpleUploadedFile(value["name"], base64.b64decode(value["file"]), getattr(value, "content_type", "application/octet-stream"))
return value
@klipstein
Owner

An alternative for passing the filename would be to use a data uri http://tools.ietf.org/html/rfc2397:

data:image/png;filename="myfile.png";base64,asfwegheghe==
@miratcan

That field saves file to database or disk?

@klipstein
Owner

If you POST/PUT the Base64 file string to a tastypie-resource that is using this Base64FileField it'll turn the Base64 string into an UploadedFile object that then can be used by model.save directly. Depending on your storage-backend of your model's file field it then either saves the file to your disk+reference string to your db (default) or to another location which is defined in your storage class.

@miratcan

Ah i see now, very nice thanks :)

@moshevolo

Anyone can provide some more info on how to use this solution?
I have a form with a file field in forms.py and then a model with a fiel field in models.py.
Do I need to create another file with the above class, and then how do I use it with the form or with the model?
Is the right thing to do is to use Base64FileField instead of FileField in my form or in my model?
And lastly when does dehydrate function actually get called?
Here is the section from forms.py:

class DocumentUploadForm(forms.Form):
document_name = forms.CharField(max_length=30, required=False)
description = forms.CharField(widget=forms.Textarea(attrs={'cols': 60, 'rows': 4}), required=False)
docfile = forms.FileField(label='Select a file', help_text='max. 40 megabytes')

And here is the section from models.py:
class Document(models.Model):
document_name = models.CharField(max_length=30, null=True)
description = models.TextField(null=True)
document = models.FileField(upload_to='documents/%Y/%m/%d')

Thanks,
Moshe

@dcale

Hey klipstein, thank you for this! In the current tastypie version (django-tastypie==0.9.15) you have to make a little change for this to work, otherwise you'll get an "dehydrate() got an unexpected keyword argument 'for_list'" exception:

change:
def dehydrate(self, bundle):

to:
def dehydrate(self, bundle, for_list):

@yuvadm

Also missing:

import mimetypes
@th0th

Any hints on checking resolution of the incoming file when using this for an image?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.