Ember.js: Upload file component

后端 未结 4 1252
梦如初夏
梦如初夏 2021-02-05 23:40

I need to create an Ember component to select a file. My page will include multiple \"upload component\"

I have read a post trying to implement that: (https://stackoverf

4条回答
  •  北海茫月
    2021-02-06 00:12

    EDIT (2015.06): Just created a new solution based on a component. This solution provides an upload button with a preview and remove icon. P.S. The fa classes are Font Awesome

    Component handlebars

    
    

    Component JavaScript

    App.AvatarPickerComponent = Ember.Component.extend({
        actions: {
            remove: function() {
                this.set("content", null);
            }
        }
    });
    
    App.InputImageComponent = Ember.TextField.extend({
        type: 'file',
    
        change: function (evt) {
            var input = evt.target;
            if (input.files && input.files[0]) {
                var that = this;
    
                var reader = new FileReader();
                reader.onload = function (e) {
                    var data = e.target.result;
                    that.set('fdata', data);
                };
                reader.readAsDataURL(input.files[0]);
            }
        }
    });
    

    Usage example

    {{avatar-picker content=model.avatar}}
    

    Old Answer

    I took Chris Meyers example, and I made it small.

    Template

    {{#view Ember.View contentBinding="foto"}}
        {{view App.FotoUp}}
        {{view App.FotoPreview width="200" srcBinding="foto"}}
    {{/view}}
    

    JavaScript

    App.FotoPreview= Ember.View.extend({
        attributeBindings: ['src'],
        tagName: 'img',
    });
    
    
    App.FotoUp= Ember.TextField.extend({
        type: 'file',
    
        change: function(evt) {
            var input = evt.target;
            if (input.files && input.files[0]) {
                var that = this;
    
                var reader = new FileReader();
                reader.onload = function(e) {
                    var data = e.target.result;
                    that.set('parentView.content', data);
                }
                reader.readAsDataURL(input.files[0]);
            }
        },
    });
    

提交回复
热议问题