使用JQuery的Django-Tasypie图像上传示例

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

到目前为止服务器端似乎正确测试CURL:

我发现这篇文章有用Django-tastypie:POST中文件上传的任何例子?

编辑:这是我用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运行以下命令:

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

现在我正在尝试使用jquery作为客户端而不是curl …..同样没有运气。 很难找到Jquery + Tastypie用于文件上传的工作示例……

如果你有任何简单的例子可以感谢分享

如果你的意思是使用$.ajax()$.post()那么它将无法工作,因为Ajax不支持文件上传。 参见例如此SOpost 。

虽然有一些解决方法 – 例如通过隐藏的iframe或基于闪存的解决方案上传表单 – 它们在上面提到的SOpost中讨论过。 虽然它们都不是完美的,所以你必须选择最适合你用例的那个。

如果将来有人偶然发现这个问题,我在github上使用这个jquery文件上传演示 ,我的图像上传工作(已经使用curl工作了)。

使用基本文件上传:

  1. 包含必要的js文件(jquery,jquery-fileupload,iframe-transport和jquery.ui.widget)。
  2. 初始化目标input[type=file]控件,如下所示

码:

 $('#fileupload').fileupload({ url: url, dataType: 'json', done: function (e, data) { $.each(data.result.files, function (index, file) { $('

').text(file.name).appendTo('#files'); }); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .progress-bar').css( 'width', progress + '%' ); } }).prop('disabled', !$.support.fileInput) .parent().addClass($.support.fileInput ? undefined : 'disabled');

这应该可以解决问题。