Skip to content

04.0.0 Upload Images

Patrick Baselier edited this page Oct 11, 2015 · 7 revisions

What you will learn

  • Create a component to select a file
  • Add an action to the Remove button

Before you start

See the installation instructions. Use tag 4.0.0.

Create a component to select a file

Ember doesn't have a helper for selecting a file, but we can create a component that extends an Ember TextField to create a file input element.

  • Open frontend/app/templates/products/show.hbs.
  • Paste the code from form.hbs in this gist into the form tag, just above the submit button.
  • Replace
<input type='file' accept='image/*'>

with

{{upload-file file=model.image accept='image/*'}}
  • In the app, edit a product.
  • Inspect the error shown in the Console tab in the browser. Ember is missing the upload-file helper, so let's create this component.
  • In the terminal, enter ember g component upload-file.
  • Open frontend/app/components/upload-file.js and replace the content with the code from upload-file.js in this gist.

Add an action to the Remove button

  • Open frontend/app/templates/products/show.hbs.
  • Change the markup for the Remove button and call the (yet to defined) removeImage action when you click it:
<button {{action 'removeImage'}} type='button' class='remove pull-right'>Remove</button>
  • In the app, edit a product and click the Remove button.
  • Inspect the error shown in the Console tab in the browser. Ember is missing the removeImage action, so let's create this.
  • Open frontend/app/controllers/products/show.js and add removeImage:
export default Ember.ObjectController.extend({
  actions: {
    toggleEditing() {
      ...
    },
    submit() {
      ...
    },
    removeImage() {
      this.model.set('image', null);
    }
  }
});
  • In the app, edit a product and click the Remove button again.