I'm having an issue uploading an image to my web application using Angular 4. I convert the input file using readAsBinaryString() and extract the ASCII code using btoa() before passing it to a backend service. While this process works smoothly on Chrome, it encounters problems on Internet Explorer 11.
To address the IE11 compatibility issue, I included the readAsBinaryString() function in the polyfills.ts file:
function str2ab(str) {
let buf = new ArrayBuffer(str.length);
let bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
if (!FileReader.prototype.readAsBinaryString) {
FileReader.prototype.readAsBinaryString = function (fileData) {
let binary = '';
let pt = this;
let reader = new FileReader();
reader.onload = function (e) {
let bytes = str2ab(reader.result);
let length = bytes.byteLength;
for (let i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
pt.content = binary;
pt.onload();
};
reader.readAsArrayBuffer(fileData);
};
}
image.component.html
<input type="file" name="image" id="image" accept="image/png, image/jpeg" (change)="fileChange($event)" [(ngModel)]="image" placeholder="Upload image">
image.component.ts
fileChange = function (evt) {
let files = evt.target.files;
let file = files[0];
if (files && file) {
let reader = new FileReader();
reader.onload = (e) => { // 'e' is undefined on ie11!
let target = <FileReader>e.target;
let result = target.result as string;
this.byteArray = btoa(result);
};
reader.readAsBinaryString(file);
}
};
By adding the polyfills, the readAsBinaryString() function now works on IE11. However, the reader.onload function throws the following error: Unable to get property 'target' of undefined or null reference.