建一個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/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