ember-cli
package, which adds attachments support to your Ember-Data models.
In the root dir of your project run
npm i ember-attachable --save-dev
,
or you can add ember-attachable
to your package.json
:
"devDependencies": {
...
"ember-attachable": "1.8.0"
}
You may want to be more precise with your version locking.
Ember-attachable
provides a mixin to be included in your models for
adding attachments support. This mixin can be imported from
your app's namespace (e.g. ../mixins/attachable
in your models):
import Ember from 'ember';
import DS from 'ember-data';
import Attachable from '../mixins/attachable';
export default DS.Model.extend(Attachable, {
attachmentAs: 'file'; // Name of your attachable attribute
});
There is a support of having two or more attachments simultaneously
on the same model. For this, just set array of strings as a value of
attachmentAs
property:
export default DS.Model.extend(Attachable, {
attachmentAs: ['file', 'photo']; // Name of your attachable attributes
});
To save your model with attachment(s), mixin adds a new method saveWithAttachement()
.
This method adheres Ember-Data
's save()
semantics, and saves your model
along with attachment:
userModel.set('photo', file) // 'photo' is the name of attachment configured in userModel's class
userModel.saveWithAttachment()
Attachment itself can be an instance of [Blob
] (https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or of any other classes which are supported by FormData
(see Working principle
below)
There may be certain situations where you need to set custom headers for the request. You can pass an object to saveWithAttachment
with these header.
Example using Ember simple auth Authorizer
this.get('session').authorize('authorizer:devise', (headerName, headerValue) => {
let authObject = {};
authObject[headerName] = headerValue;
userModel.saveWithAttachment(authObject);
});
This is an example of a simple input file component.
//component.js
import Ember from 'ember';
export default Ember.TextField.extend({
type: 'file',
file: null,
change: function (e) {
this.set('file', new Blob([e.target.files[0]],{ type: e.target.files[0].type}));
}
});
ember-attachable
internally uses FormData API
to build POST request with
Content-Type: multipart/form-data
for saving your Ember Data
models along with transferring attachment.
If you ember app is backed by Rails
application, you can use this library with paperclip gem
(or any other of your taste) to effectively manage save request on backend.