- 웹에서 파일을 업로드할 때 사용하는 Spring의 인터페이스
- multipart/form-data 형식의 데이터를 Spring이 객체로 만들어준 것
public interface MultipartFile {
// 원본 파일명 가져오기
String getOriginalFilename(); // "my-photo.jpg"
// 파일 크기 (bytes)
long getSize(); // 1024000
// 파일 내용을 byte 배열로
byte[] getBytes();
// 파일을 InputStream으로
InputStream getInputStream();
// 파일이 비어있는지 확인
boolean isEmpty();
// 파일 저장 (디스크에)
void transferTo(File dest);
// Content-Type
String getContentType(); // "image/jpeg"
}
실제 사용 예시 :
@PostMapping("/upload")
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
// 1. 파일 정보 확인
String filename = file.getOriginalFilename(); // "test.jpg"
long size = file.getSize(); // 1048576 (1MB)
String contentType = file.getContentType(); // "image/jpeg"
// 2. 파일이 비어있는지 체크
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("파일이 비어있습니다");
}
// 3. 파일 저장
String uploadDir = "/uploads/";
File destinationFile = new File(uploadDir + filename);
file.transferTo(destinationFile);
// 4. 또는 byte 배열로 처리
byte[] fileData = file.getBytes();
return ResponseEntity.ok("업로드 성공");
}