'preview image not be shown using typescript
I used this link for Convert an Image to byte array in Angular
Convert an Image to byte array in Angular (typescript)
but src not bind to image for preview my typescript code is :
upload() : void {
const file = (document.querySelector('input[type=file]') as HTMLInputElement).files![0];
const preview = document.getElementById('preview') as HTMLImageElement;
const reader = new FileReader();
let byteArray;
reader.addEventListener("loadend", function () {
// convert image file to base64 string
console.log('base64', reader.result);
**preview.src != reader.result;**
byteArray = convertDataURIToBinary(reader.result);
console.log('byte array', byteArray);
}, false);
if (file) {
reader!.readAsDataURL(file);
}
}
}
function convertDataURIToBinary(dataURI:any) {
var base64Index = dataURI.indexOf(';base64,') + ';base64,'.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(let i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
and my html is
<input type="file" id="file" accept="image/*" width="300" height="300" />
<button (click)="upload()">Upload</button>
<img id="preview">
My problem is this line that src is empty and the image not be shown
Thank you
Solution 1:[1]
Please save the reader result into a variable and use the same as the source to an img tag in HTML
TS File :
binaryImage : any;
...
this.binaryImage = reader.result;
...
HTML File:
<img src="{{binaryImage}}">
or
<div style="background-image: url({{binaryImage}});">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vince Cyriac |
