上传文件骨干力量tastypie? [英] Uploading files to tastypie with Backbone?

查看:84
本文介绍了上传文件骨干力量tastypie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一些其他的问题,我想我的tastypie资源应该是这个样子:

Checked some other questions and I think my tastypie resource should look something like this:

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 ImageResource(MultipartResource, ModelResource):

    image = fields.FileField(attribute="image")

请告诉我,如果这是错误的。

Please tell me if that's wrong.

我不明白是什么,假设以上是正确的,是要传递给资源。下面是一个文件输入:

What I don't get, assuming the above is correct, is what to pass to the resource. Here is a file input:

<input id="file" type="file" />

如果我有一个主干模型IMG做什么我设置图像?

If I have a backbone model img what do I set image to?

img.set("image", $("#file").val()); // tastypie doesn't store file, it stores a string
img.set("image", $("#file").files[0]); // get "{"error_message": "'dict' object has no attribute '_committed'" ...

怎么设置我的脊梁图像属性,这样我可以上传文件通过AJAX来tastypie?

What do I set my backbone "image" attribute to so that I can upload a file to tastypie via ajax?

推荐答案

您可以覆盖同步方法 FORMDATA API,以便能够提交文件,模型的属性。

You may override sync method to serialize with FormData api to be able to submit files as model's attributes.

请注意,它会在现代浏览器只工作。它曾与骨干0.9.2,我建议要检查默认Backbone.sync,并据此通过的想法。

Please note that it will work only in modern browsers. It worked with Backbone 0.9.2, I advise to check the default Backbone.sync and adopt the idea accordingly.

function getValue (object, prop, args) {
  if (!(object && object[prop])) return null;
  return _.isFunction(object[prop]) ?
    object[prop].apply(object, args) :
    object[prop];
}

var MultipartModel = Backbone.Model.extend({
  sync: function (method, model, options) {
    var data
      , methodMap = {
          'create': 'POST',
          'update': 'PUT',
          'delete': 'DELETE',
          'read':   'GET'
        }
      , params = {
          type: methodMap[method],
          dataType: 'json',
          url: getValue(model, 'url') || this.urlError()
        };

    if (method == 'create' || method == 'update') {
      if (!!window.FormData) {
        data = new FormData();
        $.each(model.toJSON(), function (name, value) {
          if ($.isArray(value)) {
            if (value.length > 0) {
              $.each(value, function(index, item_value) {
                data.append(name, item_value);
              })
            }
          } else {
            data.append(name, value)
          }
        });
        params.contentType = false;
        params.processData = false;
      } else {
        data = model.toJSON();
        params.contentType = "application/x-www-form-urlencoded";
        params.processData = true;
      }
      params.data = data;
    }

    return $.ajax(_.extend(params, options));
  },

  urlError: function() {
    throw new Error('A "url" property or function must be specified');
  }

});

这是从上传的观点摘录,我用&LT;输入类型=文件名称=文件多&GT; 文件上传,以便用户可以选择多个文件。后来我听的变化事件,并使用 collection.create 来上载每个文件。

This is excerpt from upload view, I use <input type="file" name="file" multiple> for file uploads so user can select many files. I then listen to the change event and use collection.create to upload each file.

var MultipartCollection = Backbone.Collection.extend({model: MultipartModel});


var UploadView = Backbone.View.extend({

  events: {
    "change input[name=file]": "changeEvent"
  },

  changeEvent: function (e) {
    this.uploadFiles(e.target.files);
    // Empty file input value:
    e.target.outerHTML = e.target.outerHTML;
  },

  uploadFiles: function (files) {
    _.each(files, this.uploadFile, this);
    return this;
  },

  uploadFile: function (file) {
    this.collection.create({file: file});
    return this;
  }

})

这篇关于上传文件骨干力量tastypie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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