2017-10-09 4 views
2

私はPDFファイルを提供する次のエンドポイントコードを持っています。ファイル/ PDFファイルの提供方法春の反応的な方法

@RequestMapping 
ResponseEntity<byte[]> getPDF() { 
    File file = ...; 
    byte[] contents = null; 
    try { 
    try (FileInputStream fis = new FileInputStream(file)) { 
     contents = new byte[(int) file.length()]; 
     fis.read(contents); 
    } 
    } catch(Exception e) { 
    // error handling 
    } 
    HttpHeaders headers = new HttpHeaders(); 
    headers.setContentDispositionFormData(file.getName(), file.getName()); 
    headeres.setCacheControl("must-revalidate, post-check=0, pre-check=0"); 
    return new ResponseEntity<>(contents, headers, HttpStatus.OK); 
} 

にはどうすれば反応型Flux/MonoDataBufferに上記変換することができます。

私は小切手DataBufferUtilsを持っていますが、必要なものを提供していないようです。私はどちらの例も見つけられませんでした。

答えて

2

これを実現する最も簡単な方法は、Resourceです。 DataBufferUtilsDataBufferUtils#read()のように、Flux<DataBuffer>InputStreamを変換するが、いくつかの便利なメソッドを持っていることを

@GetMapping(path = "/pdf", produces = "application/pdf") 
ResponseEntity<Resource> getPDF() { 
    Resource pdfFile = ...; 
    HttpHeaders headers = new HttpHeaders(); 
    headers.setContentDispositionFormData(file.getName(), file.getName()); 
    return ResponseEntity 
    .ok().cacheControl(CacheControl.noCache()) 
    .headers(headers).body(resource); 
} 

は注意してください。しかし、Resourceを扱うことはまだ優れています。

+0

ありがとう、あなたは 'リソース'が場面の裏でどのように働くか知っていますか? 「Flux/Mono」反応タイプのような背圧処理もしていますか? –

+0

はい、あります。 WebFluxにはそのための 'ResourceEncoder'があります。 –

関連する問題