Upload an image file, convert the image file into a byte array and send it to back end through post method
I tried to use the FileReader() and covert it to a array buffer. But it gave me an undifined object.
This is my button I used to upload the image. And when the form is submit I am calling onSubmit function to post the data.
<input type="file" style="display: none" accept="image/*" (change)="onFileChanged($event)" #fileInput>
<a mat-raised-button class="btn" (click)="fileInput.click()">Upload Logo</a>
<img class="btn" *ngIf="selectedFile != null" style="width: 30%; height: 3%" src="data:image/jpg;base64,{{selectedFile}}">
<img *ngIf="selectedFile == null" style="display: none">
Here is the function I used to upload the image
onFileChanged(event) {
this.selectedFile = event.target.files[0];
console.log('Selected file before:',this.selectedFile);
let reader = new FileReader();
reader.onload = function(){
let arrayBuffer = this.result;
let bytes = new Uint8Array(arrayBuffer);
console.log(bytes);
}
reader.readAsArrayBuffer(this.selectedFile);
}
Here is my onSubmit function
onSubmit() {
const data = {};
data['name'] = this.addEntityForm.value.entityCode;
data['description'] = this.addEntityForm.value.entity;
data['displayName'] = this.addEntityForm.value.eDisplayName;
if (this.selectedFile != null){
data['logo'] = this.selectedFile;
console.log('Inside the selectedFile if');
console.log(this.selectedFile);
}
else {
data['logo'] = null;
console.log('Inside the else')
}
data['status'] = 'ACTIVE';
console.log('Posted data :', data);
this.profileServise.addNewEntity(data).subscribe( result => {
if (result) {
this.globalService.updateEntityTable(result);
}
this.openSnackbar('New Entity Created Successfully');
this.matDialogRef.close();
}, error => {
this.openSnackbar('An Error in Creating a New Entity');
});
}
I want to send the uploaded image as a byte array to the back end