오늘은 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();
일단 위와 같이 해서 파일을 다운로드해서 처리를 했습니다.
즐거운 코딩되세요.
[JSTL] forEach, forTokens 정리 (1) | 2025.01.17 |
---|---|
[YAML] Boolean 변수 선언 방식 (0) | 2025.01.14 |
[eclipse tip] 정규표현식을 이용하여 특정문자열을 주석으로 처리하는 방법 (0) | 2025.01.07 |
[Logback] springboot logback 설정에 간단 정리 (0) | 2024.12.23 |
JAVA : split 함수 (1) | 2024.11.01 |