📁 파일 업로드 & 다운로드 개념 및 구현 (Spring 기반)
✅ Upload (업로드)
- 정의: 클라이언트가 서버에 데이터 또는 파일을 전송하는 행위
- Spring에서는 MultipartFile 인터페이스를 통해 파일을 수신하고 저장
📌 예시: 업로드 구현 (FileService.java)
String uuid = UUID.randomUUID().toString();
String fileName = uuid + "_" + multipartFile.getOriginalFilename().replaceAll("_", "-");
String uploadPath = System.getProperty("user.dir") + "/build/resources/main/static/upload/";
File uploadFile = new File(uploadPath + fileName);
if (!new File(uploadPath).exists()) {
new File(uploadPath).mkdir();
}
multipartFile.transferTo(uploadFile);
✅ Download (다운로드)
- 정의: 서버가 클라이언트에게 데이터 또는 파일을 전송하는 행위
- ServletOutputStream을 통해 바이트 데이터를 응답으로 전송
📌 예시: 다운로드 구현 (FileService.java)
File file = new File(uploadPath + fileName);
if (!file.exists()) return;
FileInputStream fin = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fin.read(bytes);
fin.close();
String lodFilename = fileName.split("_")[1];
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(lodFilename, "UTF-8"));
ServletOutputStream fout = response.getOutputStream();
fout.write(bytes);
fout.close();
✅ Stream (스트림)
- 정의: 데이터의 흐름을 의미하며, 파일 처리, 네트워크 통신, 입출력 등에서 사용
- 단위: byte
📌 예시
FileInputStream fin = new FileInputStream(file);
ServletOutputStream fout = response.getOutputStream();
✅ Buffer (버퍼)
- 정의: 스트림 처리 속도를 일정하게 유지하기 위한 임시 저장소
- 예시: 영상 재생 시 버퍼링, 파일 전송 시 내부적으로 사용됨
| 구분 | 설명 | 클래스 예시 |
|---|
| Input | 외부 → Java 메모리 | FileInputStream |
| Output | Java 메모리 → 외부 | ServletOutputStream |
✅ UUID (범용 고유 식별자)
- 정의: 중복되지 않는 고유한 문자열을 생성
- 용도: 파일명 중복 방지
📌 예시
String uuid = UUID.randomUUID().toString();
✅ 업로드 폴더 위치
| 구분 | 설명 |
|---|
src | 개발자가 작성한 코드 위치 |
build | 실행 시 컴파일된 코드가 위치한 서버 폴더 (파일 저장 위치) |
📌 경로 설정 예시
String baseDir = System.getProperty("user.dir");
String uploadPath = baseDir + "/build/resources/main/static/upload/";
✅ File 클래스 (Java 외부 파일 조작)
📌 주요 메서드
File file = new File("경로");
file.exists();
file.mkdir();
file.length();
file.delete();
✅ Spring Upload 구현 요약
1) MultipartFile 사용
- 대용량 바이트 파일을 매핑/조작할 때 사용하는 인터페이스
@ModelAttribute로 컨트롤러에 매핑
- 여러 파일:
List<MultipartFile>
2) 주요 메서드
multipartFile.transferTo(file);
multipartFile.getOriginalFilename();
3) application.properties 설정
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
✅ JS에서 파일 업로드 (Fetch API)
const form = document.querySelector("#uploadForm");
const formData = new FormData(form);
formData.append("file", file);
fetch("/upload", {
method: "POST",
body: formData
});
✅ Spring Download 구현 요약
1) 파일을 바이트로 읽기
FileInputStream fin = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fin.read(bytes);
fin.close();
2) 응답 헤더 설정
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
3) 클라이언트로 전송
ServletOutputStream fout = response.getOutputStream();
fout.write(bytes);
fout.close();
✅ 파일 삭제 구현
File file = new File(uploadPath + fileName);
if (file.exists()) {
file.delete();
return true;
}
return false;