클라이언트가 파일을 다운로드할 수 있도록 구현하기 위해서는 'Content-Disposition' 헤더가 필요하다. 'Content-Disposition' 헤더는 inline 또는 attachment 라는 값을 가질 수 있다.
inline의 경우 데이터를 브라우저 화면에 배치(Dispose)하겠다는 의미이며 attachment는 데이터가 첨부(attachment) 파일로서 전송되어 사용자가 파일을 다운로드 받아 컴퓨터에 저장할 수 있도록 한다.
나는 파일을 다운로드 할 수 있도록 하기 위해 'Content-Disposition'을 'attachment'로 설정하고 파일명을 알 수 있도록 filename 이라는 내용을 추가로 작성하였다.
0. Resource 클래스 활용
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@ResponseBody
@GetMapping("/download")
public ResponseEntity<Resource> download(@RequestParam String fileName){
Resource resource = new FileSystemResource("C:\\upload" + fileName);
String resourceName = resource.getFilename();
HttpHeaders headers = new HttpHeaders();
try {
headers.add("Content-Disposition", "attachment;filename=\""
+ new String(resourceName.getBytes("UTF-8"), "ISO-8859-1") + "\"");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
} catch (Exception e) {
log.error(e.getMessage());
return new ResponseEntity<Resource>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Resource>(resource, headers, HttpStatus.OK);
}
1. Byte[] 활용
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@GetMapping("/board/goHome1102")
public ResponseEntity<byte[]> home1102(@RequestParam String filename){
String fileName = "C:\\update" + filename;
InputStream is = null;
ResponseEntity<byte[]> entity = null;
HttpHeaders headers = new HttpHeaders();
try {
is = new FileInputStream(fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.add("Content-Disposition", "attachment;filename=\""
+ new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + "\"");
entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(is),
headers, HttpStatus.CREATED);
} catch (Exception e) {
log.error(e.getMessage());
entity = new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST);
} finally {
if(is != null) try{is.close();} catch(Exception e) {};
}
return entity;
}
'Java > Spring Framework' 카테고리의 다른 글
| @PathVariable (0) | 2023.02.08 |
|---|---|
| [Spring Framework] Date 타입 파라미터 (0) | 2023.02.06 |
| [Spring Framework] 파일 업로드 기본 설정 (0) | 2023.01.27 |
| [Spring Framework] @RequestBody와 @ResponseBody (0) | 2023.01.26 |
| [Spring Framework] @Mapping 어노테이션의 consumes와 procedures (0) | 2023.01.26 |