2019-10-14 18:23:29 +00:00
|
|
|
import Component from '@ember/component';
|
|
|
|
import filesize from 'filesize';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @module FileToArrayBuffer
|
|
|
|
* `FileToArrayBuffer` is a component that will allow you to pick a file from the local file system. Once
|
|
|
|
* loaded, this file will be emitted as a JS ArrayBuffer to the passed `onChange` callback.
|
|
|
|
*
|
|
|
|
* @example
|
|
|
|
* ```js
|
|
|
|
* <FileToArrayBuffer @onChange={{action (mut file)}} />
|
|
|
|
* ```
|
|
|
|
* @param onChange=null {Function} - The function to call when the file read is complete. This function
|
2021-11-15 19:52:04 +00:00
|
|
|
* receives the file as a JS ArrayBuffer
|
2019-10-14 18:23:29 +00:00
|
|
|
* @param [label=null {String}] - Text to use as the label for the file input
|
|
|
|
* @param [fileHelpText=null {String} - Text to use as help under the file input
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
export default Component.extend({
|
|
|
|
classNames: ['box', 'is-fullwidth', 'is-marginless', 'is-shadowless'],
|
|
|
|
onChange: () => {},
|
|
|
|
label: null,
|
|
|
|
fileHelpText: null,
|
|
|
|
|
|
|
|
file: null,
|
2022-12-19 23:54:59 +00:00
|
|
|
filename: null,
|
2019-10-14 18:23:29 +00:00
|
|
|
fileSize: null,
|
|
|
|
fileLastModified: null,
|
|
|
|
|
|
|
|
readFile(file) {
|
|
|
|
const reader = new FileReader();
|
2022-01-25 20:27:26 +00:00
|
|
|
// raft-snapshot-restore test was failing on CI trying to send action on destroyed object
|
|
|
|
// ensure that the component has not been torn down prior to sending onChange action
|
|
|
|
if (!this.isDestroyed && !this.isDestroying) {
|
|
|
|
reader.onload = () => this.send('onChange', reader.result, file);
|
|
|
|
}
|
2019-10-14 18:23:29 +00:00
|
|
|
reader.readAsArrayBuffer(file);
|
|
|
|
},
|
|
|
|
|
|
|
|
actions: {
|
|
|
|
pickedFile(e) {
|
2022-11-09 23:15:31 +00:00
|
|
|
const { files } = e.target;
|
2019-10-14 18:23:29 +00:00
|
|
|
if (!files.length) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
for (let i = 0, len = files.length; i < len; i++) {
|
|
|
|
this.readFile(files[i]);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
clearFile() {
|
|
|
|
this.send('onChange');
|
|
|
|
},
|
|
|
|
onChange(fileAsBytes, fileMeta) {
|
2022-11-09 23:15:31 +00:00
|
|
|
const { name, size, lastModifiedDate } = fileMeta || {};
|
|
|
|
const fileSize = size ? filesize(size) : null;
|
2019-10-14 18:23:29 +00:00
|
|
|
this.set('file', fileAsBytes);
|
2022-12-19 23:54:59 +00:00
|
|
|
this.set('filename', name);
|
2019-10-14 18:23:29 +00:00
|
|
|
this.set('fileSize', fileSize);
|
|
|
|
this.set('fileLastModified', lastModifiedDate);
|
|
|
|
this.onChange(fileAsBytes, name);
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|