I have a simple UI where when a user enters a name and presses a button, a get request is sent and I would like the image from that get request to be rendered in the browser. However, that image is not being rendered. Below is my UI:
When the button is pressed, the following error appears in the console:
GET data:image/jpeg;base64,undefined net::ERR_INVALID_URL
Below is my component file:
@Component({
selector: 'home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {
data:any
image:any
retrievedImage: any;
base64Data: any;
retrieveResonse: any;
imageName:any;
constructor(private imageData:imageService,
private httpClient:HttpClient) { }
ngOnInit(): void {
console.log(this.image)
this.imageData.getImages().subscribe((results)=>{
console.log(results)
this.data = results
})
}
getImage2() {
//Make a call to Sprinf Boot to get the Image Bytes.
this.httpClient.get('http://localhost:8080/get/' + this.imageName,
{responseType:'blob'})
.subscribe(
res => {
this.retrieveResonse = res;
this.base64Data = this.retrieveResonse.picByte;
this.retrievedImage = 'data:image/jpeg;base64,' + this.base64Data;
}
);
}
}
Below is my HTML file:
<p>
<mat-toolbar>
<span>Image Repository</span>
</mat-toolbar>
</p>
<button mat-button style="position:relative; left: 5px; top:2px" (click)="getImage2()">Get an image </button>
<input #image type="text" style="position:relative;left:10px; top: 2.99px" [(ngModel)]="imageName">
<!-- <img *ngIf="image" style="position:relative;top:200px" [src]="image" alt="Place image title">
-->
<div class="container row">
<div class="col-md-12">
<div *ngIf=retrievedImage>
<img [src]="retrievedImage" style="position:relative;top:200px" src="data:image/png;base64,{{image}}">
</div>
</div>
</div>
How would I go about fixing this error? I'm not sure why the image would be undefined.
Edit: It looks like the this.base64data variable is showing up as undefined but I am not sure why
As mentioned in the comments, the response is just the bytes. In this case, I believe you can use the endpoint URL right in the img.src
.
export class HomeComponent implements OnInit {
imageUrl: string;
getImage2() {
//Update the image url
this.imageUrl= 'http://localhost:8080/get/' + this.imageName;
}
}
<div class="container row">
<div class="col-md-12">
<div *ngIf=retrievedImage>
<img [src]="imageUrl" style="position:relative;top:200px" src="data:image/png;base64,{{image}}">
</div>
</div>
</div>