Reputation: 3429
I am using Spring Boot and Angular 4. I have uploaded an image to the project location. When I try to view the uploaded image, it is not displayed but an error is thrown. How can I view the image?
ang.html:
<button type="button" class="button btn-info"
(click)='showInfo()'>ShowImages</button>
<div class="panel panel-primary">
<div class="panel-heading">List of Images</div>
<img [src]="fileUploads">
</div>
components.ts:
fileUploads: any;
sid: number = 1;
showInfo() {
this.drugservice.getFiles(this.sid).subscribe(data => {this.fileUploads = data, alert(data)}), err => {
console.log('Error Occured showInfo');
};
}
service.ts
getFiles(id: number): any {
return this.http.get(this.getFileuploadedURL+'/'+id, { responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'image/png' })
});
}
springBoot Controller:
@GetMapping(value = "/getUploadfiles/{id}")
@ResponseBody
public byte[] getImage(@PathVariable Integer id) throws IOException {
String filename = "01";
System.out.println("id : " + id);
File serverFile = new File(rootLocation + "\\" + filename + ".jpg");
System.out.println("serverFile : " + serverFile);
return Files.readAllBytes(serverFile.toPath());
}
Upvotes: 3
Views: 2676
Reputation: 111
Try updating your mapping in spring boot controller to:
@GetMapping(value = "/getUploadfiles/{id}", produces = MediaType.IMAGE_JPEG_VALUE)
this will indicate that the returned object must be handled as a JPEG image.
In Angular create the required path to image and pass is to the img element, eg:
components.ts:
fileUrl = '/getUploadfiles/1';
ang.html:
<img [src]="fileUrl">
Upvotes: 2