Django-Tasypie图像上传示例与JQuery [英] Django-Tasypie image upload example with JQuery

查看:117
本文介绍了Django-Tasypie图像上传示例与JQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种实现从jquery到Django-Tastypie的客户端文件(图像)上传的方法。

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

到目前为止,服务器端似乎正确使用CURL进行测试:

So far server side seems correct testing with CURL:

我发现这篇文章helpfull

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

编辑:这是我用curl - >

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)

然后使用curl运行以下命令: p>

Then running the following command with curl :

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

现在我试图用jQuery作为客户端,而不是卷曲.....没有运气。
很难找到Jquery + Tastypie的文件上传工作示例...

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

推荐答案

如果您的意思是使用 $。ajax() $ .post()然后它将无法工作,因为Ajax不支持文件上传。参见例如此SO发布

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.

虽然有一些解决方法 - 例如在隐藏的iframe或基于闪存的解决方案中通过表单上传 - 它们在上述SO文章中讨论。没有一个是完美的,所以你必须选择最适合你的用例。

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.

这篇关于Django-Tasypie图像上传示例与JQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆