Search code examples
jquerydjangofile-uploadtastypie

Django-Tasypie image upload example with JQuery


I'm looking for a way to implement client side file (image) upload from jquery to Django-Tastypie.

So far server side seems correct testing with CURL:

I found this post helpfull Django-tastypie: Any example on file upload in POST?

EDIT : This is what i did with curl ->

in api.py :
    class MultipartResource(object):
        def deserialize(self, request, data, format=None):
            if not format:
                format = request.META.get('CONTENT_TYPE', 'application/json')
            if format == 'application/x-www-form-urlencoded':
                return request.POST
            if format.startswith('multipart'):
                data = request.POST.copy()
                data.update(request.FILES)
                return data
            return super(MultipartResource, self).deserialize(request, data, format)


    class FooResource(MultipartResource, ModelResource):
        img = fields.FileField(attribute="img", null=True, blank=True)
        class Meta:
            queryset = Foo.objects.all()
            authorization= Authorization()


in models.py :
class Foo(models.Model):
    img = models.ImageField(upload_to="images", null=True, blank=True)
    body = models.CharField(max_length=255)

Then running the following command with curl :

curl -v  -F "body=test" -F "img=@my_picture.png" http://localhost:8000/api/v1/foo/

Now i'm trying to do the same with jquery as client instead of curl.....with no luck. It's difficult to find a working example for Jquery+Tastypie for file upload...

If you have any simple example available thanks for sharing


Solution

  • If you mean using $.ajax() or $.post() then it won't work because Ajax doesn't support file uploads. See e.g. this SO post.

    There are some workarounds though - e.g. uploading via form in hidden iframe or flash-based solutions - they are discussed in the SO post mentioned above. None of them are perfect though, so you will have to choose the one which best serves your use case.