개발관련/java 개발관련
[Spring tip]Content-Disposition 가 안 받아질때
후니의 개발이야기
2025. 2. 19. 16:07
728x90
반응형
오늘은 springboot 를 이용해서 api로 해서 file을 다운로드 시키는 것을 테스트하던중에 알게된 것입니다.
InputStream inputStream1 = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream1.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] fileBytes = outputStream.toByteArray();
// HTTP 응답 헤더 설정
HttpHeaders headers = new HttpHeaders();
headers.add("Access-Control-Allow-Origin", "*");
headers.add("Content-Disposition", "attachment; filename=" + rtnFileName);
return new ResponseEntity <>(fileBytes, headers, HttpStatus.OK);
위와 같이 header 를 설정하고 내려 줬는데 front 쪽에서 filename을 받을 수 없다고 해서 알게된 것입니다.
front 에서 header 쪽 Content-Disposition 값을 못 받을때는 header에 한개를 더 추가해야합니다.
headers.add("Access-Control-Expose-Headers", "Content-Disposition");
Access-Control-Expose-Headers를 header에 추가를 하니 front쪽에서 파일을 잘 가져다 쓰더라구요.
front에 적용된 일부분도 첨부해드릴께요
then(response => {
// 응답 헤더에서 Content-Type과 Content-Disposition을 가져옴
const contentType = response.headers.get('Content-Type');
const contentDisposition = response.headers.get('Content-Disposition');
const [, encodedFileNamePart] = contentDisposition.split('filename=');
// UTF-8 문자를 제거한다.
const replaceUtf8 = encodedFileNamePart.replace(/UTF-8/g, '');
// 작음따옴표를 제거한다.
const replaceSingleQuote = replaceUtf8.replace(/''/g, '');
// 인코딩 된 fileName을 디코딩한다.
filename = decodeURIComponent(replaceSingleQuote);
// 파일을 blob 형태로 변환
return response.blob();
일단 위와 같이 해서 파일을 다운로드해서 처리를 했습니다.
즐거운 코딩되세요.

728x90