Currently, I am working on a Client-Server application that utilizes SpringBoot and Angular2. One of the functionalities I have implemented successfully is loading an image from the server based on its filename.
At the client-side, I store the attribute image:string and display it in the template. However, there is a concern with return res.url;, as it does not utilize the actual resource, which may not be the correct approach.
My main goal is to implement image caching. As far as I know, web browsers can cache images automatically. Despite this, my current setup does not seem to be working in terms of caching. If anyone has any suggestions or insights on what adjustments are needed, please feel free to share them.
On the Server side (SpringBoot):
public class ImageRestController {
@RequestMapping(value = "/getImage/{filename:.+}", method = RequestMethod.GET)
public ResponseEntity<Resource> getImage(@PathVariable String filename) {
try {
String path = Paths.get(ROOT, filename).toString();
Resource loader = resourceLoader.getResource("file:" + path);
return new ResponseEntity<Resource>(loader, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<Resource>(HttpStatus.NOT_FOUND);
}
}
}
On the Client side (Angular2):
@Component({
selector: 'my-image',
template: `
<img src="{{image}}"/>
`
})
export class MyComponent {
image:string;
constructor(private service:MyService) {}
showImage(filename:string) {
this.service.getImage(filename)
.subscribe((file) => {
this.image = file;
});
}
}
export class MyService() {
getImage(filename:String):Observable<any> {
return this.http.get(imagesUrl + "getImage/" + filename)
.map(this.extractUrl)
.catch(this.handleError);
}
extractUrl(res:Response):string {
return res.url;
}
}