【问题标题】:Angular get image from Spring RestController and cache itAngular 从 Spring RestController 获取图像并缓存它
【发布时间】:2016-11-09 15:35:58
【问题描述】:

我有一个使用 SpringBoot 和 Angular2 的客户端-服务器应用程序。 我想按文件名从服务器加载图像。这很好用。

我将属性 image:string 存储在客户端,然后再次将其放入模板中。 你可能会注意return res.url;;我没有使用实际的资源,这可能是错误的。

我的目标是缓存图像。据我了解,网络浏览器可以自动缓存图像。正确的? 但是缓存还没有工作,也许有人可以给我一个提示需要调整什么? 是否需要不同的标头?

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

客户端(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;
  }
}

【问题讨论】:

  • 您可以尝试向您已经服务过一次的客户发送HttpStatus.NOT_MODIFIED

标签: java spring typescript angular spring-boot


【解决方案1】:

你可以在服务器端做这样的事情(如果你能得到这些信息,也许可以添加一个 ETag 或 Last-Modified 标头):

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

请参阅HTTP caching part of the reference documentation in Spring

如果您只是提供资源而不应用任何其他逻辑,那么您最好执行以下操作:

@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());
    }

}

the other relevant part of the reference documentation。您还可以应用转换并利用缓存清除 (see this section as well)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-06
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多