Skip to content

Instantly share code, notes, and snippets.

@mupkoo
Last active October 11, 2018 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mupkoo/f2ce2bd88f98640a9b1c4b3f372720f5 to your computer and use it in GitHub Desktop.
Save mupkoo/f2ce2bd88f98640a9b1c4b3f372720f5 to your computer and use it in GitHub Desktop.
Attachments input
import Component from '@ember/component';
import { computed } from '@ember/object';
import { or } from '@ember/object/computed';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency';
import { Promise, all } from 'rsvp';
import S3Uploader from 'ember-uploader/uploaders/s3';
export default Component.extend({
notify: service('satellite-notify'),
session: service(),
// Actions
onchange: () => {},
signingUrl: '/api/v1/uploads/sign',
multiple: true,
disabled: false,
_disabled: or('uploadTask.isRunning', 'disabled'),
_attachments: computed('attachments.[]', function () {
return this.attachments || [];
}),
_documents: computed('attachments.[]', function () {
return this._attachments.filter((attachment) => this._isImage(attachment));
}),
_photos: computed('attachments.[]', function () {
return this._attachments.filter((attachment) => !this._isImage(attachment));
}),
uploadingCount: computed('uploadTask.{numQueued,numRunning}', function () {
return this.uploadTask.numQueued + this.uploadTask.numRunning;
}),
uploadTask: task(function * (file) {
// Do this in parallel
let [response, meta] = yield all([
this._createUploader().upload(file),
this._isImage(file) ? this._getImageDimensions(file) : {}
]);
let { size, name, type } = file;
let extension = file.name.split('.').pop();
let path = response.querySelector('Key').textContent;
this.onchange([...this._attachments, { name, path, extension, size, type, meta }]);
}).maxConcurrency(3).enqueue(),
enqueueForUpload({ target: { files }}) {
for (let i = 0; i < files.length; i++) {
this.uploadTask.perform(files[i]);
}
},
removeAttachment(attachment) {
let attachments = this._attachments.filter((attachmentItem) => attachmentItem !== attachment);
this.onchange(attachments);
},
_createUploader() {
return S3Uploader.create({
signingAjaxSettings: { headers: this.session.requestHeaders() },
signingUrl: this.signingUrl
});
},
_getImageDimensions(file) {
return new Promise((resolve) => {
let reader = new FileReader();
let image = new Image();
reader.onload = () => image.src = reader.result;
image.onload = () => resolve({ width: image.width, height: image.height });
reader.readAsDataURL(file);
});
},
_isImage(file) {
return file.type.indexOf('image/') === 0;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment