Ember.js value binding with HTML5 file upload

后端 未结 2 506
耶瑟儿~
耶瑟儿~ 2021-01-01 01:58

I am not far from it to get the file upload working with Ember-data. But I do not get the value binding right. Below the relevant code.

This is the App.js

2条回答
  •  抹茶落季
    2021-01-01 02:28

    I updated your code to the following:

    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]);
        }
    });
    

    In the App.UploadFile instead of reference the controller directlly, I set the file property. So you can bind your model property, with the view using:

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

    The Ember.run is used to you don't have problems when testing the app.

    Please give a look in that jsfiddle http://jsfiddle.net/marciojunior/LxEsF/

    Just fill the inputs and click in the save button. And you will see in the browser console, the data that will be send to the server.

提交回复
热议问题