@ResponseBody
@GetMapping("test")
@ResponseBody
public String test(HttpServletResponse response) throws IOException {
return "helloworld";
}
파일 다운로드
GalleryController
@GetMapping("down/{no}")
@ResponseBody
public void down(@PathVariable int no, HttpServletResponse response) throws IOException {
GalleryVo g = galleryRepository.getGallery(no);
System.out.println(g);
if(g == null) {
response.sendError(400);
}
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(g.getfName(), "UTF-8") + "\"");
response.setHeader("Content-Length", String.valueOf(g.getfSize()));
File file = new File("D:\\uploadForSpring", String.valueOf(no));
byte[] data = FileUtils.readFileToByteArray(file);
response.getOutputStream().write(data);
}
@GetMapping("down/{no}")
public ResponseEntity down(@PathVariable int no) throws IOException {
GalleryVo g = galleryRepository.getGallery(no);
System.out.println(g);
if(g == null) {
return ResponseEntity.notFound().build();
}
File file = new File("D:\\uploadForSpring", String.valueOf(no));
byte[] data = FileUtils.readFileToByteArray(file);
ByteArrayResource res = new ByteArrayResource(data);
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(g.getfSize())
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(g.getfName(), "UTF-8") + "\"")
.header(HttpHeaders.CONTENT_ENCODING, "UTF-8")
.body(res);
}
GalleryVo를 바탕으로 파일 전송
방법1) HttpServletResponse response로 처리
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(파일이름, "UTF-8") + "\"");
response.setHeader("Content-Length", String.valueOf(파일사이즈));
File file = new File("D:\\uploadForSpring", String.valueOf(no));
byte[] data = FileUtils.readFileToByteArray(file);
response.getOutputStream().write(data);
방법2) 스프링에서 ResponseEntity로 처리
ByteArrayResource res = new ByteArrayResource(data);
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(g.getfSize())
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(g.getfName(), "UTF-8") + "\"")
.header(HttpHeaders.CONTENT_ENCODING, "UTF-8")
.body(res);