2016-07-07 6 views
1

SpringBoot와 Angular2를 사용하는 클라이언트 - 서버 어플리케이션이 있습니다. 파일 이름으로 서버에서 이미지를로드하고 싶습니다. 이것은 잘 작동합니다.Spring RestController에서 이미지를 얻고 캐시하십시오.

클라이언트에 이미지 : 문자열 문자열을 저장하고 템플릿에 다시 저장합니다. 주의 할 점은 입니다. 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; 
    } 
} 
+0

이미 한 번 서비스 한 클라이언트에'HttpStatus.NOT_MODIFIED'를 보내보십시오. – rinukkusu

답변

1

당신은 서버 측에서 같은 것을 할 (그리고 당신이 할 수있는 경우에 아마의 ETag 또는 마지막 수정 헤더를 추가 할 수 있습니다) 정보를 얻을 :

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)를 활용할 수도 있습니다.

+0

고맙습니다. – Johannes

관련 문제