프로그램/JAVA

[Spring] JAVA 대용량 파일 다운로드

프뚜 2022. 9. 1. 21:42
728x90
반응형
SMALL

안녕하세요!

프뚜(프로그래머 뚜)입니다!

 

[개발 환경]

 - OS: windows 10 64bit

 - JAVA: v1.8

 - SpringBoot: v2.7.3

 

Spring (Boot)에서 대용량 파일을 다운로드 받을 때 사용하는 소스입니다.

 

 

- 프로젝트 구조

프로젝트명: petoo
 - src/main/java/tistory/TestController
 - URI: /file/download (GET)

 

 

- 프로젝트 > TestController 소스

// 2022.09.01[프뚜]: 01. 파일 경로를 지정 > 동영상, 이미지 등 모든 파일 가능
String path = "D:\\ffmpeg\\1.mp4";
File file = new File(path);

// 2022.09.01[프뚜]: 02. 다운로드 되거나 로컬에 저장되는 용도로 쓰이는지를 알려주는 헤더
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());

// 2022.09.01[프뚜]: 03. 파일 읽기
FileInputStream fileInputStream = new FileInputStream(path);
OutputStream out = response.getOutputStream();

// 2022.09.01[프뚜]: 04. 1024바이트씩 계속 읽으면서 outputStream 저장
int read = 0;
byte[] buffer = new byte[1024];
while ((read = fileInputStream.read(buffer)) != -1) {
    out.write(buffer, 0, read);
}

 

파일을 다운 받을 때 사용하는 소스입니다.

 

 

해당 프로젝트는 gitlab에 제공되고 있습니다. (포스팅 제목과 Git History는 1:1 매칭입니다.)
https://github.com/JeongSeongSoo/spring-tistory.git

 

GitHub - JeongSeongSoo/spring-tistory

Contribute to JeongSeongSoo/spring-tistory development by creating an account on GitHub.

github.com


궁금하신 부분 또는 문제가 생긴 부분에 대해서 댓글 남겨주시면 빠르고 정확한 답변드리겠습니다.

728x90
반응형
LIST