Ember.js值与HTML5文件上传绑定

时间:2013-11-11 14:55:29

标签: javascript html5 ember.js

我与文件上传工作在Ember-data上的距离并不远。但我没有得到正确的价值绑定。相关代码下方。

这是App.js

App.LandcodeNewRoute = Ember.Route.extend({
    model: function () {
        return this.store.createRecord('landcode');
    },
    actions: {
        saveLandcode: function () {
            this.currentModel.save();
        }
    }
});


// REST & Model
App.ApplicationAdapter = DS.RESTAdapter.extend({
    namespace: 'api'
});
App.Store = DS.Store.extend({
    adapter: 'App.ApplicationAdapter'
});

App.Landcode = DS.Model.extend({
    code: DS.attr('string'),
    image: DS.attr('string')
});

// Views
App.UploadFile = Ember.TextField.extend({
    tagName: 'input',
    attributeBindings: ['name'],
    type: 'file',
    change: function (e) {
        var reader, that;
        that = this;
        reader = new FileReader();
        reader.onload = function (e) {
            var fileToUpload = e.target.result;

            console.log(e.target.result); // this spams the console with the image content
            console.log(that.get('controller')); // output: Class {imageBinding: Binding,

            that.get('controller').set(that.get('name'), fileToUpload);
        };
        return reader.readAsText(e.target.files[0]);
    }
});

HTML

<script type="text/x-handlebars" data-template-name="landcode/new">
    Code: {{input value=code}}<br />
    Image: {{view App.UploadFile name="image" imageBinding="Landcode.image" }}
    <button {{action 'saveLandcode'}}>Save</button>
</script>

正如您在 HTML 部分中看到的那样,我尝试将imagecontent绑定到Landcode模型属性图像。没有资本L也尝试过它。

我认为我不能这样绑定图像,因为它是一个自定义视图对象?而且通常它会自动绑定我认为。也许我只做两次事情。

参考文献:

  1. http://emberjs.com/api/classes/Ember.Binding.html

  2. http://devblog.hedtek.com/2012/04/brief-foray-into-html5-file-apis.html

  3. File upload with Ember data

  4. How: File Upload with ember.js

  5. http://discuss.emberjs.com/t/file-uploads-is-there-a-better-solution/765

  6. http://chrismeyers.org/2012/06/12/ember-js-handlebars-view-content-inheritance-image-upload-preview-view-object-binding/

2 个答案:

答案 0 :(得分:10)

我将您的代码更新为以下内容:

App.LandcodeNewRoute = Ember.Route.extend({
    model: function () {        
        return this.store.createRecord('landcode');
    },
    actions: {
        saveLandcode: function () {
            this.currentModel.save();
        }
    }
});

// REST & Model
App.ApplicationAdapter = DS.RESTAdapter.extend({
    namespace: 'api'    
});

App.Landcode = DS.Model.extend({
    code: DS.attr('string'),
    image: DS.attr('string')
});

// views
App.UploadFile = Ember.TextField.extend({
    tagName: 'input',
    attributeBindings: ['name'],
    type: 'file',
    file: null,
    change: function (e) {
        var reader = new FileReader(), 
        that = this;        
        reader.onload = function (e) {
            var fileToUpload = e.target.result;
            Ember.run(function() {
                that.set('file', fileToUpload);
            });            
        };
        return reader.readAsDataURL(e.target.files[0]);
    }
});

App.UploadFile而不是直接引用控制器,我设置了file属性。因此,您可以使用以下命令绑定模型属性:

{{view App.UploadFile name="image" file=image }}

Ember.run用于测试应用时没有问题。

请查看jsfiddle http://jsfiddle.net/marciojunior/LxEsF/

只需填写输入并单击“保存”按钮。您将在浏览器控制台中看到将发送到服务器的数据。

答案 1 :(得分:1)

我发现使用将数据URI附加到模型属性不允许上载超过大约60k的文件。相反,我最终为ember-data编写了一个表单数据适配器。这将使用FormData上传所有模型数据。很抱歉,这是在CoffeeScript而不是JS,但它是从我的博客文章中粘贴的。你可以在http://blog.mattbeedle.name/posts/file-uploads-in-ember-data/

阅读整篇文章
`import ApplicationAdapter from 'appkit/adapters/application'`

get = Ember.get

FormDataAdapter = ApplicationAdapter.extend
  ajaxOptions: (url, type, hash) ->
    hash = hash || {}
    hash.url = url
    hash.type = type
    hash.dataType = 'json'
    hash.context = @

    if hash.data and type != 'GET' and type != 'DELETE'
      hash.processData = false
      hash.contentType = false
      fd = new FormData()
      root = Object.keys(hash.data)[0]
      for key in Object.keys(hash.data[root])
        if hash.data[root][key]
          fd.append("#{root}[#{key}]", hash.data[root][key])

      hash.data = fd

    headers = get(@, 'headers')
    if headers != undefined
      hash.beforeSend = (xhr) ->
        for key in Ember.keys(headers)
          xhr.setRequestHeader(key, headers[key])

    hash

`export default FormDataAdapter`