2017-07-17 69 views
0

@GetMapping(值= 「/圖片」,產生= 「應用程序/ PDF格式」) @ResponseBody 公共字符串downloadFile(@PathVariable( 「路徑」)字符串路徑)拋出IOException異常{ClassPathResource downloadLink = new ClassPathResource(「/ assets /」+ path);如何從Web服務下載圖像/ PDF文件中的Spring應用程序

HttpHeaders headers = new HttpHeaders(); 
    headers.setContentType(MediaType.parseMediaType("application/pdf")); 
    headers.add("Access-Control-Allow-Origin", "*"); 
    headers.add("Access-Control-Allow-Methods", "GET, POST, PUT"); 
    headers.add("Access-Control-Allow-Headers", "Content-Type"); 
    headers.add("Content-Disposition", "filename=" + path); 
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); 
    headers.add("Pragma", "no-cache"); 
    headers.add("Expires", "0"); 

    headers.setContentLength(downloadLink.contentLength()); 
    Base64.getDecoder().decode(path); 
    return "/admin/image"; 
} 

回答

0

我檢查你的代碼的代碼幾乎是正確的,但你需要修改一些代碼片段,您可以使用下載文件此示例代碼:您可以參考這個代碼

@RestController 
@RequestMapping("/download") 
public class DownloadFileRestController { 
    @Autowired 
    ServletContext context; 

    @RequestMapping(value = "/pdf/{fileName:.+}", method = RequestMethod.GET, produces = "application/pdf") 
    public ResponseEntity<InputStreamResource> download(@PathVariable("fileName") String fileName) throws IOException { 
     System.out.println("Calling Download:- " + fileName); 
     ClassPathResource pdfFile = new ClassPathResource("downloads/" + fileName); 
     HttpHeaders headers = new HttpHeaders(); 
     headers.setContentType(MediaType.parseMediaType("application/pdf")); 
     headers.add("Access-Control-Allow-Origin", "*"); 
     headers.add("Access-Control-Allow-Methods", "GET, POST, PUT"); 
     headers.add("Access-Control-Allow-Headers", "Content-Type"); 
     headers.add("Content-Disposition", "filename=" + fileName); 
     headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); 
     headers.add("Pragma", "no-cache"); 
     headers.add("Expires", "0"); 

     headers.setContentLength(pdfFile.contentLength()); 
     ResponseEntity<InputStreamResource> response = new ResponseEntity<InputStreamResource>(new InputStreamResource(pdfFile.getInputStream()), headers, HttpStatus.OK); 
     return response; 

    } 
} 
+0

時,出現了base64字符串,我需要將其轉換爲文件並在html頁面上呈現。我無法看到代碼 –

+0

中的轉換,您可以在解碼後發送數據:'ResponseEntity response = new ResponseEntity (new String(Base64.getDecoder()。decode(pdfFile.getInputStream()。toString())),headers, HttpStatus.OK); ' – Sharma

相關問題