2019-07-02 14:38:42 +02:00
|
|
|
import { DirectUpload } from '@rails/activestorage';
|
2019-02-13 14:16:22 +01:00
|
|
|
import ProgressBar from './progress-bar';
|
|
|
|
|
|
|
|
/**
|
|
|
|
Uploader class is a delegate for DirectUpload instance
|
2020-01-08 18:15:03 +01:00
|
|
|
used to track lifecycle and progress of an upload.
|
2019-02-13 14:16:22 +01:00
|
|
|
*/
|
|
|
|
export default class Uploader {
|
|
|
|
constructor(input, file, directUploadUrl) {
|
|
|
|
this.directUpload = new DirectUpload(file, directUploadUrl, this);
|
|
|
|
this.progressBar = new ProgressBar(input, this.directUpload.id, file);
|
|
|
|
}
|
|
|
|
|
|
|
|
start() {
|
|
|
|
this.progressBar.start();
|
|
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
2020-04-09 12:50:47 +02:00
|
|
|
this.directUpload.create((errorMsg, attributes) => {
|
|
|
|
if (errorMsg) {
|
|
|
|
this.progressBar.error(errorMsg);
|
|
|
|
reject(new Error(errorMsg));
|
2019-02-13 14:16:22 +01:00
|
|
|
} else {
|
|
|
|
resolve(attributes.signed_id);
|
|
|
|
}
|
|
|
|
this.progressBar.end();
|
|
|
|
this.progressBar.destroy();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
uploadRequestDidProgress(event) {
|
|
|
|
const progress = (event.loaded / event.total) * 100;
|
|
|
|
if (progress) {
|
|
|
|
this.progressBar.progress(progress);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
directUploadWillStoreFileWithXHR(xhr) {
|
|
|
|
xhr.upload.addEventListener('progress', event =>
|
|
|
|
this.uploadRequestDidProgress(event)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|