如何在spring应用程序中从web服务下载image / pdf文件

时间:2017-07-17 16:23:48

标签: java spring rest web thymeleaf

@GetMapping(value =“/ image”,produce =“application / pdf”)     @ResponseBody     public String downloadFile(@PathVariable(“path”)String path)抛出IOException {         ClassPathResource downloadLink = new ClassPathResource(“/ assets /”+ path);

    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";
}

1 个答案:

答案 0 :(得分: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;

    }
}