Reputation: 19660
I have built a browser umd library using webpack.
I am listening to an onchange event of an input file. When someone submits an image/file it will convert it to base64. I am trying to make this as seemless as possible so i am using promises and await/async from https://blog.shovonhasan.com/using-promises-with-filereader/.
However, there is a problem - When i call the convertToBase64 function no response is being received. The promise is not returning a reject or resolve. There are no errors being thrown and the line with console.log(data) is not being hit.
html
<input id="hs-pay" type="file" accept="image/*" capture="camera">
<script type="text/javascript">
let hsp = new HSPay();
</script>
index.js
var HSFileReader = require('./helper/fileReader');
class HSPay {
constructor() {
this.fileReader = new HSFileReader();
this.imageInput = document.getElementById('hs-pay');
if (!this.imageInput) {
throw "Error(input): hs-pay could not be found:"
}
this.imageInput.addEventListener("change", this.uploadImage.bind(this));
}
async uploadImage() {
try {
let data = await this.fileReader.convertToBase64(this.imageInput.files[0]);
console.log("data", data);
} catch (e) {
console.log(e);
}
}
}
module.exports = HSPay;
filereader.js
class HSFileReader {
constructor() {
this.fileReader = new FileReader();
}
convertToBase64(file) {
if (!file) {
throw "Error(input): file could not be found:"
}
return new Promise((resolve, reject) => {
this.fileReader.readAsDataURL(file);
this.fileReader.onerror = () => {
reject("Problem parsing input file.");
};
this.fileReader.onloadEnd = () => {
resolve(this.fileReader.result);
};
});
}
}
module.exports = HSFileReader;
Upvotes: 0
Views: 143
Reputation: 7916
According to MDN, onloadend
is a method of FileReader
. onloadEnd
(uppercase E) would never be called, and thus, resolve
would never be called.
Upvotes: 2