download a file from spring boot controllers

URL Link //n.sfs.tw/11168

2017-06-03 15:25:18 By igogo

 

建一個static 文件夾, 位置如圖, 把example.pdf 放進去

 

 

 

 

 @RequestMapping(path = "/download", method = RequestMethod.GET)
    public ResponseEntity<?> download(String param) throws IOException {
        File file = new File("static/報名簡章.pdf");
        if (file.exists()) {
            logger.info(file.getAbsolutePath());
        } else {
            logger.info("no");
        }

        Path path = Paths.get(file.getAbsolutePath());
        ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

        HttpHeaders headers = new HttpHeaders();
        String filename = new String("報名簡章.pdf".getBytes("UTF-8"), "ISO_8859_1");
        
        headers.setContentDispositionFormData("attachment", filename);
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/pdf"))
                .body(resource);

    }

 

參考

https://stackoverflow.com/questions/35680932/download-a-file-from-spring-boot-rest-service/35683261#35683261

https://stackoverflow.com/questions/5673260/downloading-a-file-from-spring-controllers

關於java String 

String objects in Java don't have an encoding (*).

The only thing that has an encoding is a byte[].

https://stackoverflow.com/questions/5729806/encode-string-to-utf-8