기록을 합시다.
[Spring] 여러 File Upload 하고, 저장하기 본문
요약해서 말해보자면, Spring Framework에서 자주 사용하는 commons-fileupload라는 라이브러리의 MultipartFile 인터페이스를 이용하여 업로드된 파일들을 서버에서 처리해주는 과정을 간단히 적었다.
사전 사항(다른 버전이면 commons-fileupload 다른 버전 사용을 해야함)
Spring Tool Suite 3.9.14 - New and Noteworthy
Spring Tool Suite 3.9.14 - New and Noteworthy
Spring Tool Suite 3.9.14: New and Noteworthy Important Note This is a minor bugfix and maintenance release that we ship to our existing STS3 users beyond the announced maintenance lifespan for your convenience. We strongly recommend to update to the new Sp
docs.spring.io
pom.xml
프로젝트 바로 아래의 pom.xml에 아래의 dependency 2개를 추가해준다.
<dependencies>
...
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
...
</dependencies>
commons-io
Apache Commons 프로젝트의 하나로, Java에서 파일과 스트림 처리를 더 쉽게 만드는 다양한 클래스 제공한다.
commons-io의 기능 중 일부는 다음과 같다.
- 파일과 디렉토리 작업 (복사, 이동, 삭제, 비어 있는지 확인 등)
- 파일 필터 (파일 크기, 수정 날짜, 확장자 등)
- I/O 작업 (스트림 복사, 라인 단위로 읽기, 문자열과 바이트 배열 변환 등)
- 리소스 관리 (자원 해제 및 닫기)
commons-fileuplad
Java 웹 애플리케이션에서 파일 업로드를 위한 라이브러리 중 하나이다.
특히 commons-fileupload에서 MultipartFile을 사용하면 업로드된 파일의 메타데이터와 파일 내용을 읽어올 수 있다.
보통 Spring 프레임워크에서는 MultipartFile을 사용하며, 이를 이용해 다음과 같은 작업을 할 수 있다.
- 파일 업로드 시 업로드된 파일의 이름, 크기, MIME 타입 등의 메타데이터 추출
- 업로드된 파일을 디스크에 저장하거나 메모리에 로드하여 사용
- 업로드된 파일에 대한 유효성 검사
root-context.xml
<beans>
...
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1073700000" />
<property name="maxInMemorySize" value="104857600" />
</bean>
...
</beans>
- 다운로드한 dependency를 bean에다가 등록해줘서 스프링 프레임워크에서 쓸 수 있게 해준다. 파일 업로드를 처리하는 CommonsMultipartResolver를 bean으로 등록하였다.
- maxUploadSize는 업로드 할 수 있는 파일의 최대 크기를 지정해준다.
- maxInMemorySize는 업로드 한 파일이 메모리에 보관될 최대 크기를 지정해준다.
html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
function FileUpload(){
document.FileForm.action='/board/fileUpload';
document.FileForm.submit();
}
</script>
<link rel="stylesheet" href="/resources/css/board.css">
<meta charset="UTF-8">
<title>파일 업로드 예제</title>
</head>
<form name="FileForm" method="post" enctype="multipart/form-data">
<input type="text" name="painter" value="데이비드자뱅">
<input type="file" name="fileUpload" multiple><br>
<input type="button" onclick="FileUpload()" value="파일 전송">
</form>
<body>
</body>
</html>
![](https://blog.kakaocdn.net/dn/rWexz/btscPYvy7zf/Ie2iXecAQDraQMI1R2mdyK/img.png)
- html 파일에서 fileupload를 할 수 있도록 input 태그의 type을 file로 해준다.
- button을 눌러서 submit하기 위해 onclick에 FileUpload() 함수를 등록해주었다.
- FileUpload 함수는 FileForm을 /board/fileUpload로 보내준다.
Controller 파일
package com.SFTest.controller;
import java.io.File;
public class BoardController {
@GetMapping("/board/fileUpload")
public void getfileUpload() throws Exception {
}
@PostMapping("/board/fileUpload")
public void postfileUpload(@RequestParam("painter") String painter,@RequestParam("fileUpload") List<MultipartFile> multipartFile) throws Exception {
String path = "c:\\Repository\\file\\";
if(!multipartFile.isEmpty()) {
File targetFile = null;
for(MultipartFile mpr:multipartFile) {
String org_filename = mpr.getOriginalFilename();
//String org_fileExtension = org_filename.substring(org_filename.lastIndexOf("."));
//String stored_filename = UUID.randomUUID().toString().replaceAll("-", "") + org_fileExtension;
long filesize = mpr.getSize();
targetFile = new File(path + org_filename);
mpr.transferTo(targetFile);
//콘솔로 파일 잘 도착 되었는지 확인
System.out.println("filesize : "+filesize);
System.out.println("targetfile : "+targetFile);
}
}
}
코드 설명
@GetMapping("/board/fileUpload")
public void getfileUpload() throws Exception {}
- get 요청을 받으면 board 폴더 안에 있는 fileupload.jsp 파일을 매핑해준다.
@PostMapping("/board/fileUpload")
public void postfileUpload(@RequestParam("painter") String painter,
@RequestParam("fileUpload") List<MultipartFile> multipartFile
) throws Exception
- post 요청을 받으면 board 폴더 안에 있는 fileupload.jsp파일을 또 매핑시켜준다.
- @RequestParam을 통해, html 태그 안에 적어준 name을 적어서, form data를 받아온다. 특히나 fileupload 데이터를 받아올 때는, List<MultipartFile>형식으로 받아와야 한다.
String path = "c:\\Repository\\file\\";
- 로컬 컴퓨터의 폴더를 path로 설정해준다. 나는 C드라이브 바로 아래의 Repository에 file 폴더로 지정해주었다.
if(!multipartFile.isEmpty()) {
File targetFile = null;
for(MultipartFile mpr:multipartFile) {
String org_filename = mpr.getOriginalFilename();
long filesize = mpr.getSize();
targetFile = new File(path + org_filename);
mpr.transferTo(targetFile);
System.out.println("filesize : "+filesize);
System.out.println("targetfile : "+targetFile);
}
}
- if문에서는 multipartfile이 비어있는지 확인해준다.(그런데 js로 먼저 유효성 검사하는 게 더 나을 것 같..)
- for문에서는 배열으로 이루어진 multipartFile안의 아이템인 mpr을 경로 안의 폴더에 저장해준다.
- System.out.println은 데이터가 잘 들어있는지 확인하기 위해서 적었다.
결과
![](https://blog.kakaocdn.net/dn/YAVGx/btscHRELKGR/ukPdgEW59jETwqZcYAKtq0/img.png)
![](https://blog.kakaocdn.net/dn/2GYAR/btscPZBnJnj/ekd5nKlmajlXirpkBGnce0/img.png)
폴더를 보면 파일이 아주 잘 도착했다.
'공부 > Java' 카테고리의 다른 글
[Spring] IntelliJ에서 Auto-Reloading 하기 (0) | 2023.05.13 |
---|---|
[Spring] Spring Framework에서 Form 받아오기 (0) | 2023.04.27 |
[Spring] DAO, DTO, VO (0) | 2023.04.27 |
[Spring] Windows11 스프링 프레임워크 기본 세팅하기 (0) | 2023.04.26 |
[Spring] Spring Framework 기본 (1) | 2023.04.25 |