File Upload in EmberJs

Hi,

I want to make file upload in emberjs.There are various inbuilt components out there…but they really doesnt serve my purpose as i want to post some other fields too with the file also.

Also i want to act after the form request is complete when i get the some response from the server. There are methods by creating formdata variable introduced in html5…

that lets you create an ajax request

Can you suggest how to do that in ember as in plain javascript it looks quite easy.

I have had great success wrapping blueimp file uploader into a EmberJS component. You simply need to setup the jQuery plugin on didInsertElement, example code is as follows:

.... = Em.Component.extend({
  didInsertElement: function() {
    var self = this;
    $('.file-uploader').fileupload({
      dataType: 'json',
      method: 'POST',
      url: '/urlhere',
      paramName: 'file',
      submit: function (e, data) {
        data.formData = {id: 123, title: 'abc123'};
        data.jqXHR = this.fileupload('send', data);
        return false;
      },
      done: function (e, data) {
        console.log('success!');
        self.sendAction('saveComplete');
      },
      fail: function (e, data) {
        console.log('failed', e);
        self.sendAction('saveFailed');
      }
    });
  },

  willDestroyElement: function() {
    $('.file-uploader').fileupload('destroy');
  },
}
...

This of course is a basic example that requires a component class and template but should give you an example of how to wire everything up.

1 Like

But i need to send some other fields too along with the file upload to the same url in the same request??

That’s what this line is doing: data.formData = {id: 123, title: 'abc123'};

You can attach any other details you want by setting data.formData before calling this.fileupload('send', data)

thanks…thats looks a good way suppose…

I’m working on an addon which you can use in your ember-data model to support attachments out of the box https://github.com/abuiles/ember-attachable

I’ve had a pretty good experience using EmberDroplet. It needs the FileReader API to work but can be polyfilled. It also comes with a HTML5 drag n drop UI out of the box.

Not sure if this is still needed, but I happen to have written an article about file upload with ember.js and ember data:

http://webcloud.info/blog/2015/03/09/ember-drag-drop-file-upload-the-rightish-way/

Thanks for the code !

I was able to implement working component .

-components/x-file-upload.js

EmTasks.XFileUploadComponent = Ember.Component.extend({
    actions: {
        destroyAttachment: function(id) {
            var store = this.get("targetObject.store");

            if (confirm("Are you sure?")) {
                store.find('attachment', id).then(function (attachment) {
                    attachment.destroyRecord()
                });
            }
        }
    },
    didInsertElement: function() {
        var self = this;
        $('.file-uploader').fileupload({
            dataType: 'json',
            method: 'POST',
            url: '/attachments',
            paramName: 'file',
            autoUpload: true,
            add: function (e, data) {
                //console.log("add: e, data", e, data);
                data.submit();
            },
            submit: function (e, data) {
                //console.log("jquery submit this, self", $(this), self, self.task);
            },
            done: function (e, data) {
                var store = self.get("targetObject.store");
                var attachment = data.result.attachment;
                attachment.task = self.task;

                store.push("attachment", attachment);
                self.sendAction('saveComplete');
            },
            fail: function (e, data) {
                console.log('failed', e);
                self.sendAction('saveFailed');
            }
        });
    },

    willDestroyElement: function() {
        $('.file-uploader').fileupload('destroy');
    }
});

-templates/components/x-file-upload.handlebars

<span class="btn btn-success fileinput-button">
    <form>
      <i class="glyphicon glyphicon-plus"></i>
      <span>Select files...</span>

      <!-- The file input field used as target for the file upload widget -->
      <input id="fileupload" class='file-uploader' type="file" name="files[]" multiple>

      <input name="task_id" type='hidden' value='{{task.id}}'>
    </form>
</span>

<br/>

<div class='col-md-8'>
    <h4><i class="fa fa-file fa-lg"></i> Załączniki</h4>
</div>

{{#each task.attachments as |attachment|}}
    <div class="col-md-8">
        <div class='col-md-8'>
            {{attachment.file_name}}
        </div>

        <a href='{{attachment.url}}' target='_blank'>
            <i class="fa fa-download"></i> Ściągnij
        </a>
        &nbsp;

        <a {{action 'destroyAttachment' attachment.id }} class='clickable'>
            <i class="fa fa-times"></i>Usuń
        </a>

    </div>
{{/each}}

<div class='col-md-12'>
    <hr />
</div>

-usage in parent template

        <div role="tabpanel" class="tab-pane" id="attachments">
            {{x-file-upload task=model}}
        </div>

Everything works:

  • adding new file
  • list of attachments is refreshed
  • deletion also works

:smiley:


I didn’t have luck with any tutorials, too many things to change and they require installation various external things.

The bad news is that I don’t use Ember CLI, so 90% working libraries won’t work for me.

That’s funny, in Angular I can download raw source and re-use it.

But in Ember I have to obligatory use Ember CLI - I don’t like, I don’t want to install it to small/medium app. Too much hassle for this temp project.

That’s not true, you can use Ember without Ember CLI. You just can’t make use of all the amazing addons out there (easily).

There is a project that does allow you to use addons without using Ember CLI as well. GitHub - ef4/ember-giftwrap: A tool for packaging Ember addons

Sorry I wasn’t clear in reply…

I mean:

But in Ember I have to obligatory use Ember CLI TO INSTALL LIBRARIES - I don’t like, I don’t want to install it to small/medium app. Too much hassle for this temp project.

90+% libraries use Ember CLI, you can’t download raw source and re-use it in plain Rails app. Period.


There is a project that does allow you to use addons without using Ember CLI as well. GitHub - ef4/ember-giftwrap: A tool for packaging Ember addons

Nice :smile:

The Ember addons ecosystem is one of the best things about Ember. But users stuck on legacy build systems have a hard time taking advantage of it.

This tool is intended to be able to take any set of Ember addons and package them in a standalone JS file that can be injected directly into any Ember app, no matter how it was built.

Thanks for link, :slight_smile: but in readme I have info that it is alpha :slight_smile:

This is a work-in-progress. It’s alpha quality. Feedback appreciated.

Anyway I could use that before, right now everything is working for me. I wrote components that use raw libraries (bootstrap datetimepicker / bootstrap tabs etc).

But there is a problem with Blueimp file uploader. Whenever there is change in the input element during fileupload _replaceFileInput (a internal method) function is executed , which clones the input element and replaces the old input tag, so when there is change in attributes for file-upload component , this.$() has reference to the old input element, this causes major problem .

Component not able to updateany properties like this.$().fileupload(‘disable’), which wont work since new cloned element reference is not updated to ember component scope.