Reputation: 1549
I have application built on Ember.js (2.13)
. I have User
model and at this moment I work on avatar upload feature. When I modify model and save it then Ember makes PATCH
request to my API during it Ember
serializer builds nice json-api
object and I like it.
When I need to upload image to server I need to make some PUT
request to my API with file data I could use jQuery
ajax for this. Server will resize and crop image and save it on disk or push it to S3
bucket. But I do not like this way because this request will be created bypassing Ember's serializer and without references to model. So I need to set uploaded filename to User
model and save it then I'll have redundant request to server.
I have an idea to transform file to base64
string in Ember.js app and set this string to User
model and save it. In this case I'll have one request to server. Is this good way to upload file?
Please advice best practice of uploading files in Ember.js
application.
Upvotes: 0
Views: 237
Reputation: 5991
But I do not like this way because this request will be created bypassing Ember's serializer and without references to model.
There is nothing you can do about this - ember data does not support files. And in many situations ED is not good enough (for example - nested resource URIs, partial updates). I suggest to not be bothered about it too much - if your can't perform some request using ember data, just use Ember.$.ajax
.
So I need to set uploaded filename to User model and save it then I'll have redundant request to server.
No, you don't. Just configure your backend to return full user model (as you do for other get/post/update requests which use ED), and pass result (if request was successful, of course) to pushPayload method of the store
. Store will be updated with actual data without additional requests. Example:
this.get('session').authorize('authorizer:token', (headerName, headerValue) => {
const headers = {};
headers[headerName] = headerValue;
/*Instead of data object, you will create a formData*/
const data = {
/*Some data*/
};
Ember.$.ajax(
{
url: '/path-to-resource/id-of-resource',
headers,
type: "PUT",
data
}
)
.then(
(payload) => {
this.store.pushPayload(payload);
},
(response) => {
this.set('errorMessage', stringifyError(response));
}
)
.always(() => {
this.set('isLoading', false);
});
});
UPD: There is an addon, ember-cli-form-data which claims to add support of file upload to ember data. I didn't try it myself, so can't say if it works and how good.
Upvotes: 1
Reputation: 12872
You can give it try using popular ember addon for this.
ember-plupload and ember-uploader addon
Upvotes: 1