Spring_09_File처리

OngTK·2025년 9월 14일

Spring

목록 보기
9/25

📁 파일 업로드 & 다운로드 개념 및 구현 (Spring 기반)


✅ Upload (업로드)

  • 정의: 클라이언트가 서버에 데이터 또는 파일을 전송하는 행위
  • Spring에서는 MultipartFile 인터페이스를 통해 파일을 수신하고 저장

📌 예시: 업로드 구현 (FileService.java)

// UUID 생성 → 파일명 중복 방지
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 (버퍼)

  • 정의: 스트림 처리 속도를 일정하게 유지하기 위한 임시 저장소
  • 예시: 영상 재생 시 버퍼링, 파일 전송 시 내부적으로 사용됨

✅ Java Input / Output

구분설명클래스 예시
Input외부 → Java 메모리FileInputStream
OutputJava 메모리 → 외부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(); // 지정 경로에 파일이 존재 여부를 boolean 으로 반환

// 폴더 생성
file.mkdir(); // 지정한 파일 경로를 생성, 경로가 존재하지 않으면 폴더를 생성함

// 파일 크기 확인
file.length(); //지정 파일의 용량(Byte)를 long 타입으로 반환

// 파일 삭제
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");
// 자바와 통신할 경우, From 마크업 내 **name 속성명과 dto 멤버변수 명이 일치**해야 함

const formData = new FormData(form);
// : 일반 form을 byte 타입의 DataForm으로 변환

formData.append("file", file);
// 속성 추가

fetch("/upload", {
  method: "POST",
  body: formData
});
// header 생략 가능 : { "Content-Type" : "multipart/form-data" }

✅ Spring Download 구현 요약

1) 파일을 바이트로 읽기

// Java가 다운로드 받을 파일을 Byte로 가져옴
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;

profile
2025.05.~K디지털_풀스택 수업 수강중

0개의 댓글