简体   繁体   English

Angular从Spring RestController获取图像并缓存它

[英]Angular get image from Spring RestController and cache it

I have a Client-Server application using SpringBoot and Angular2. 我有一个使用SpringBoot和Angular2的Client-Server应用程序。 I would like to load a image from the server by filename. 我想通过文件名从服务器加载图像。 This works fine. 这很好用。

I store the attribute image:string at the client and I place it in the template again. 我将属性image:string存储在客户端,然后再次将其放入模板中。 You might pay attention to return res.url; 你可能会注意返回res.url; ; ; I do not use the actual ressource, which might be wrong. 我不使用实际的资源,这可能是错误的。

My objective is that image is cached. 我的目标是缓存图像。 To my understanding the web-browser can automatically cache the images. 据我所知,网络浏览器可以自动缓存图像。 Correct? 正确? But the caching does not work yet and maybe somebody could give me a hint what needs to be adjusted? 但是缓存还没有工作,也许有人可以给我一个需要调整的提示? Is a different header required? 是否需要不同的标题?

Server (SpringBoot) 服务器(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);
        }
    }
}   

Client (Angular2) 客户(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;
  }
}

You could do something like this on the server side (and perhaps add an ETag or Last-Modified header if you can get that information): 您可以在服务器端执行类似的操作(如果可以获取该信息,可以添加ETag或Last-Modified标头):

return ResponseEntity
            .ok()
            .cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
            .body(loader);

See the HTTP caching part of the reference documentation in Spring . 请参阅Spring中参考文档HTTP缓存部分

If you're just serving resources and not applying any additional logic, then you'd better do the following: 如果您只是提供资源而不应用任何其他逻辑,那么您最好执行以下操作:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/getImage/**")
                .addResourceLocations("classpath:/path/to/root/")
                .setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS).cachePublic());
    }

}

See the other relevant part of the reference documentation . 请参阅参考文档的其他相关部分 You can also apply transformations and leverage cache busting ( see this section as well ). 您还可以应用转换并利用缓存清除( 请参阅本节 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM