I am working in Aurelia and I have to locate an image and save in JSON type array on submission.
I am unfamiliar to handle images in array because array cannot handle images and we have to convert image to base64 binary but how to do this i do not know. Your help will be helpful for me.
<div>
<div>
<label>Active</label><br>
<input type="checkbox">
</div>
<div class="mr-3">
<a class="thumbnail">
<img src="../../../assets/images/default-user.png" width="100" alt="">
</a>
</div>
<div class="col-md-8">
<div class="radio">
<input type="radio" name="choice" checked> Keep
</div>
<div class="radio">
<input type="radio" name="choice"> Change
</div>
<span class="form-group">
<input type="file" class="mt-3" id="exampleInputFile" files.bind="">
</span>
<button class="btn btn-danger" click.delegate="submit()" >Submit</button>
</div>
Array Format
this.list = {
"a_Rows": [
{
"pkiCustomerID": "1",
"simage": "",
},
Try using HTML5 Canvas (the example code is in Typescript):
<input type="file" ... files.bind="selectedFiles" change.delegate="inputChange()">
In template JavaScript:
export class MyTemplate {
selectedFiles!:FileList;
inputChange() {
let image = new Image();
image.onload = function () {
let elem = this as HTMLImageElement;
let canvas = <HTMLCanvasElement> document.createElement('canvas');
canvas.width = elem.naturalWidth;
canvas.height = elem.naturalHeight;
let context = <CanvasRenderingContext2D> canvas.getContext('2d');
context.drawImage(elem, 0, 0);
let stringImg = canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');
};
let file = this.selectedFiles.item(0);
if (file !== null)
image.src = URL.createObjectURL(file);
}
}
stringImg
is the result you are looking for.
UPDATE:
An example for putting the result back to list
:
export class MyTemplate {
private stringImg: string = ''; // <------ ADDED
private list: any; // <------ ADDED
selectedFiles!:FileList;
inputChange() {
let image = new Image();
let _this = this; // <------ ADDED
image.onload = function () {
let elem = this as HTMLImageElement;
let canvas = <HTMLCanvasElement> document.createElement('canvas');
canvas.width = elem.naturalWidth;
canvas.height = elem.naturalHeight;
let context = <CanvasRenderingContext2D> canvas.getContext('2d');
context.drawImage(elem, 0, 0);
_this.stringImg = canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''); // <------ MODIFIED
};
let file = this.selectedFiles.item(0);
if (file !== null)
image.src = URL.createObjectURL(file);
}
submit() { // <------ ADDED
this.list = {
"a_Rows": [
{
"pkiCustomerID": "1",
"simage": this.stringImg,
},
]
}
}
}