2016-08-16 54 views
-2

路徑=上傳/文件/ 38c84b59-101b-4606-8fe7-3328f1871c03.pdf春天的ResourceLoader如何從目錄中查看PDF文件

@RequestMapping(method = RequestMethod.GET, value = "/explorer/file/{id:.+}") 
     @ResponseBody 
     public ResponseEntity<?> getFile(@PathVariable Integer id) { 
      String filename = explorerService.getById(id).getPath(); 
      try { 
       return ResponseEntity.ok(resourceLoader.getResource("file:" + filename)); 
      } catch (Exception e) { 
       return ResponseEntity.notFound().build(); 
      } 
     } 

,而不是PDF它給一些文字

非常感謝提前

screenshot

+1

有些文字?什麼文字?小心詳細說明問題 –

+0

您可以通過以下鏈接:https://www.mkyong.com/spring/spring-resource-loader-with-getresource-example/和http://stackoverflow.com/questions/32468057 /加載-A-PDF功能於瀏覽器從-A-文件中最服務器的文件系統。希望它能幫助你。 – SkyWalker

+0

一些編碼文本 –

回答

2

以與主要問題的意見,以正式的答案。重要的是,瀏覽器正在發送接受:*/*或至少application/pdf或它會在請求上發出錯誤。

@RequestMapping(method = RequestMethod.GET, value = "/explorer/file/{id:.+}", produces = "application/pdf") 
@ResponseBody 
public ResponseEntity<?> getFile(@PathVariable Integer id) { 
    String filename = explorerService.getById(id).getPath(); 
    try { 
     return ResponseEntity.ok(resourceLoader.getResource("file:" + filename)); 
    } catch (Exception e) { 
     return ResponseEntity.notFound().build(); 
    } 
} 
+0

HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(「application/pdf」));返回新的ResponseEntity <>(resourceLoader.getResource(「file:」+ filename),headers,HttpStatus.OK);你是對的謝謝 –