일반적으로 사용하는 HTML Form을 통한 파일 업로드를 이해하려면 먼저 폼을 전송하는 다음 두 가지 방식의 차이를 이해해야 한다.
application/x-www-form-urlencoded
multipart/form-data
application/x-www-form-urlencoded
방식은 HTML 폼 데이터를 서버로 전송하는 가장 기본적인 방법이다. Form 태그에 별도의 enctype
옵션이 없으면 웹 브라우저는 요청 HTTP 메시지의 헤더에 다음 내용을 추가한다.Content-Type: application/x-www-form-urlencoded
username=kim&age=20
와 같이 &
로 구분해서 전송한다.enctype="multipart/form-data"
를 지정해야 한다.multipart/form-data
방식은 다른 종류의 여러 파일과 폼의 내용을 함께 전송할 수 있다.Content-Disposition
이라는 항목별 헤더가 추가되어 있고 여기에 부가 정보가 있다. 예제에서는 username
, age
, file1
이 각각 분리되어 있고, 폼의 일반 데이터는 각 항목별로 문자가 전송되고, 파일의 경우 파일 이름과 Content-Type이 추가되고 바이너리 데이터가 전송된다. multipart/form-data
는 이렇게 각각의 항목을 구분해서, 한번에 전송하는 것이다.@Slf4j
@Controller
@RequestMapping("/servlet/v1")
public class ServletUploadControllerV1 {
@GetMapping("/upload")
public String newFile() {
return "upload-form";
}
@PostMapping("/upload")
public String saveFileV1(HttpServletRequest request)
throws ServletException, IOException {
log.info("request={}", request);
String itemName = request.getParameter("itemName");
log.info("itemName={}", itemName);
Collection<Part> parts = request.getParts();
log.info("parts={}", parts);
return "upload-form";
}
}
request.getParts()
: multipart/form-data
전송 방식에서 각각 나누어진 부분을 받아서 확인할 수 있다.<form th:action method="post" enctype="multipart/form-data">
<ul>
<li>상품명 <input type="text" name="itemName"></li>
<li>파일<input type="file" name="file" ></li>
</ul>
<input type="submit"/>
</form>
application.properties
에 다음 추가logging.level.org.apache.coyote.http11=debug
//결과 로그
Content-Type: multipart/form-data; boundary=----xxxx
------xxxx
Content-Disposition: form-data; name="itemName"
Spring
------xxxx
Content-Disposition: form-data; name="file"; filename="test.data"
Content-Type: application/octet-stream
sdklajkljdf...
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB
SizeLimitExceededException
)가 발생한다.max-file-size
: 파일 하나의 최대 사이즈, 기본 1MBmax-request-size
: 멀티파트 요청 하나에 여러 파일을 업로드 할 수 있는데, 그 전체 합이다. 기본 10MBspring.servlet.multipart.enabled=false
application/x-www-form-urlencoded
보다 훨씬 복잡하다. spring.servlet.multipart.enabled
옵션을 끄면 서블릿 컨테이너는 멀티파트와 관련된 처리를 하지 않는다. 그래서 아래의 결과 로그를 보면 request.getParameter("itemName")
, request.getParts()
의 결과가 비어있다.//결과 로그
request=org.apache.catalina.connector.RequestFacade@xxx
itemName=null
parts=[]
spring.servlet.multipart.enabled=true
(기본 true)request.getParameter("itemName")
의 결과도 잘 출력되고, request.getParts()
에도 요청한 두가지 멀티파트의 부분 데이터가 포함된 것을 확인할 수 있다. 이 옵션을 켜면 복잡한 멀티파트 요청을 처리해서 사용할 수 있게 제공한다.HttpServletRequest
객체가 RequestFacade
-> StandardMultipartHttpServletRequest
로 변한 것을 확인할 수 있다.//결과 로그
request=org.springframework.web.multipart.support.StandardMultipartHttpServletR
equest
itemName=Spring
parts=[ApplicationPart1, ApplicationPart2]
spring.servlet.multipart.enabled
옵션을 켜면 스프링의 DispatcherServlet
에서 멀티파트 리졸버(MultipartResolver
)를 실행한다.HttpServletRequest
를 MultipartHttpServletRequest
로 변환해서 반환한다.MultipartHttpServletRequest
는 HttpServletRequest
의 자식 인터페이스이고, 멀티파트와 관련된 추가 기능을 제공한다.MultipartHttpServletRequest
인터페이스를 구현한 StandardMultipartHttpServletReqeust
를 반환한다.HttpServletRequest
대신에 MultipartHttpServletRequest
를 주입받을 수 있는데, 이것을 사용하면 멀티파트와 관련된 여러가지 처리를 편리하게 할 수 있다. 그런데 이후 설명할 MultipartFile
이라는 것을 사용하는 것이 더 편하기 때문에 MultipartHttpServletRequest
를 잘 사용하지는 않는다.서블릿이 제공하는
Part
에 대해 알아보고 실제 파일도 서버에 업로드 해보자.
file.dir=파일 업로드 경로
(application.properties)file.dir=/Users/Jim/study/file/
file.dir=C:/Users/Jim/study/file/
@Slf4j
@Controller
@RequestMapping("/servlet/v2")
public class ServletUploadControllerV2 {
@Value("${file.dir}")
private String fileDir;
@GetMapping("/upload")
public String newFile() {
return "upload-form";
}
@PostMapping("/upload")
public String saveFileV1(HttpServletRequest request)
throws ServletException, IOException {
log.info("request={}", request);
String itemName = request.getParameter("itemName");
log.info("itemName={}", itemName);
Collection<Part> parts = request.getParts();
log.info("parts={}", parts);
for (Part part : parts) {
log.info("==== PART ====");
log.info("name={}", part.getName());
Collection<String> headerNames = part.getHeaderNames();
for (String headerName : headerNames) {
log.info("header {}: {}", headerName, part.getHeader(headerName));
}
//편의 메서드
//content-disposition; filename
log.info("submittedFilename={}", part.getSubmittedFileName());
log.info("size={}", part.getSize()); //part body size
//데이터 읽기
InputStream inputStream = part.getInputStream();
String body = StreamUtils.copyToString(inputStream,
StandardCharsets.UTF_8);
log.info("body={}", body);
//파일에 저장하기
if (StringUtils.hasText(part.getSubmittedFileName())) {
String fullPath = fileDir + part.getSubmittedFileName();
log.info("파일 저장 fullPath={}", fullPath);
part.write(fullPath);
}
inputStream.close();
}
return "upload-form";
}
}
Part
)으로 나누어 전송한다. parts
에는 이렇게 나누어진 데이터가 각각 담긴다.Part
는 멀티파트 형식을 편리하게 읽을 수 있는 다양한 메서드를 제공한다.part.getSubmittedFileName()
: 클라이언트가 전달한 파일명part.getInputStream()
: Part의 전송 데이터를 읽을 수 있다.part.write(...)
: Part를 통해 전송된 데이터를 저장할 수 있다.//결과 로그
==== PART ====
name=itemName
header content-disposition: form-data; name="itemName"
submittedFileName=null
size=7
body=상품A
==== PART ====
name=file
header content-disposition: form-data; name="file"; filename="스크린샷.png"
header content-type: image/png
submittedFileName=스크린샷.png
size=112384
body=qwlkjek2ljlese...
파일 저장 fullPath=/Users/kimyounghan/study/file/스크린샷.png
http://localhost:8080/servlet/v2/upload
에서 다음 내용을 전송했다.itemName
: 상품A
file
: 스크린샷.png
logging.level.org.apache.coyote.http11=debug
log.info("body={}", body);
Part
는 편하기는 하지만, HttpServletRequest
를 사용해야 하고, 추가로 파일 부분만 구분하려면 여러가지 코드를 넣어야 한다. 이번에는 스프링이 이 부분을 얼마나 편리하게 제공하는지 확인해보자.스프링은
MultipartFile
이라는 인터페이스로 멀티파트 파일을 매우 편리하게 지원한다.
@Slf4j
@Controller
@RequestMapping("/spring")
public class SpringUploadController {
@Value("${file.dir}")
private String fileDir;
@GetMapping("/upload")
public String newFile() {
return "upload-form";
}
@PostMapping("/upload")
public String saveFile(@RequestParam String itemName,
@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
log.info("request={}", request);
log.info("itemName={}", itemName);
log.info("multipartFile={}", file);
if (!file.isEmpty()) {
String fullPath = fileDir + file.getOriginalFilename();
log.info("파일 저장 fullPath={}", fullPath);
file.transferTo(new File(fullPath));
}
return "upload-form";
}
}
@RequestParam MultipartFile file
@RequestParam
을 적용하면 된다.@ModelAttribute
에서도 MultipartFile
을 동일하게 사용할 수 있다.file.getOriginalFilename()
: 업로드 파일 명file.transferTo(...)
: 파일 저장//실행 로그
request=org.springframework.web.multipart.support.StandardMultipartHttpServletR
equest@5c022dc6
itemName=상품A
multipartFile=org.springframework.web.multipart.support.StandardMultipartHttpSe
rvletRequest$StandardMultipartFile@274ba730
파일 저장 fullPath=/Users/kimyounghan/study/file/스크린샷.png
요구사항
- 상품을 관리
- 상품 이름
- 첨부파일 하나
- 이미지 파일 여러개
- 첨부파일을 업로드 다운로드 할 수 있다.
- 업로드한 이미지를 웹 브라우저에서 확인할 수 있다.
@Data
public class Item {
private Long id;
private String itemName;
private UploadFile attachFile;
private List<UploadFile> imageFiles;
}
@Repository
public class ItemRepository {
private final Map<Long, Item> store = new HashMap<>();
private long sequence = 0L;
public Item save(Item item) {
item.setId(++sequence);
store.put(item.getId(), item);
return item;
}
public Item findById(Long id) {
return store.get(id);
}
}
@Data
public class UploadFile {
private String uploadFileName;
private String storeFileName;
public UploadFile(String uploadFileName, String storeFileName) {
this.uploadFileName = uploadFileName;
this.storeFileName = storeFileName;
}
}
uploadFileName
: 고객이 업로드한 파일명storeFileName
: 서버 내부에서 관리하는 파일명@Component
public class FileStore {
@Value("${file.dir}")
private String fileDir;
public String getFullPath(String fileName) {
return fileDir + fileName;
}
public List<UploadFile> storeFiles(List<MultipartFile> multipartFiles)
throws IOException {
List<UploadFile> storeFileResult = new ArrayList<>();
for (MultipartFile multipartFile : multipartFiles) {
if (!multipartFile.isEmpty()) {
storeFileResult.add(storeFile(multipartFile));
}
}
return storeFileResult;
}
public UploadFile storeFile(MultipartFile multipartFile) throws IOException {
if (multipartFile.isEmpty()) {
return null;
}
String originalFilename = multipartFile.getOriginalFilename();
String storeFileName = createStoreFileName(originalFilename);
multipartFile.transferTo(new File(getFullPath(storeFileName)));
return new UploadFile(originalFilename, storeFileName);
}
private String createStoreFileName(String originalFilename) {
String uuid = UUID.randomUUID().toString();
String ext = extractExt(originalFilename);
return uuid + "." + ext;
}
private String extractExt(String originalFilename) {
int pos = originalFilename.lastIndexOf(".");
return originalFilename.substring(pos + 1);
}
}
createStoreFileName()
: 서버 내부에서 관리하는 파일명은 유일한 이름을 생성하는 UUID
를 사용해서 충돌하지 않도록 한다.extractExt()
: 확장자를 별도로 추출해서 서버 내부에서 관리하는 파일명에도 붙여준다.@Data
public class ItemForm {
private Long itemId;
private String itemName;
private MultipartFile attachFile;
private List<MultipartFile> imageFiles;
}
List<MultipartFile> imageFiles
: 이미지를 다중 업로드 하기 위해 MultipartFile
을 사용했다.MultipartFile attachFile
: 멀티파트는 @ModelAttribute
에서 사용할 수 있다.@Slf4j
@Controller
@RequiredArgsConstructor
public class ItemController {
private final ItemRepository itemRepository;
private final FileStore fileStore;
@GetMapping("/items/new")
public String newItem(@ModelAttribute ItemForm form) {
return "item-form";
}
@PostMapping("/items/new")
public String saveItem(@ModelAttribute ItemForm form,
RedirectAttributes redirectAttributes) throws IOException {
UploadFile attachFile = fileStore.storeFile(form.getAttachFile());
List<UploadFile> storeImageFiles =
fileStore.storeFiles(form.getImageFiles()); //파일은 aws s3
//데이터베이스에 저장
Item item = new Item();
item.setItemName(form.getItemName());
item.setAttachFile(attachFile);
item.setImageFiles(storeImageFiles);
itemRepository.save(item);
redirectAttributes.addAttribute("itemId", item.getId());
return "redirect:/items/{itemId}";
}
@GetMapping("/items/{id}")
public String items(@PathVariable Long id, Model model) {
Item item = itemRepository.findById(id);
model.addAttribute(item);
return "item-view";
}
//보안에 취약 -> 체크 로직 필요
@ResponseBody
@GetMapping("/images/{filename}")
public Resource downloadImage(@PathVariable String filename)
throws MalformedURLException {
return new UrlResource("file:" + fileStore.getFullPath(filename));
}
@GetMapping("/attach/{itemId}")
public ResponseEntity<Resource> downloadAttach(@PathVariable Long itemId)
throws MalformedURLException {
Item item = itemRepository.findById(itemId);
String storeFileName = item.getAttachFile().getStoreFileName();
String uploadFileName = item.getAttachFile().getUploadFileName();
UrlResource resource
= new UrlResource("file:" + fileStore.getFullPath(storeFileName));
log.info("uploadFileName={}", uploadFileName);
String encodedUploadFileName
= UriUtils.encode(uploadFileName, StandardCharsets.UTF_8);
String contentDisposition
= "attachment; filename=\"" + encodedUploadFileName +"\"";
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.body(resource);
}
}
@GetMapping("/items/new")
: 등록 폼을 보여준다.@PostMapping("/items/new")
: 폼의 데이터를 저장하고 보여주는 화면으로 리다이렉트 한다.@GetMapping("/items/{id}")
: 상품을 보여준다.@GetMapping("/images/{filename}")
: <img>
태그로 이미지를 조회할 때 사용. UrLResource
로 이미지 파일을 읽어서 @ResponseBody
로 이미지 바이너리를 반환한다.@GetMapping("/attach/{itemId}")
: 파일을 다운로드 할 때 실행한다. 예제를 더 단순화 할 수 있지만, 파일 다운로드 시 권한 체크같은 복잡한 상황까지 가정한다 생각하고 이미지 id
를 요청하도록 했다. 파일 다운로드시에는 고객이 업로드한 파일 이름으로 다운로드 하는게 좋다. 이때는 Content-Disposition
헤더에 attachment; filename="업로드 파일명"
값을 주면 된다.<form th:action method="post" enctype="multipart/form-data">
<ul>
<li>상품명 <input type="text" name="itemName"></li>
<li>첨부파일<input type="file" name="attachFile" ></li>
<li>이미지 파일들<input type="file" multiple="multiple" name="imageFiles" ></li>
</ul>
<input type="submit"/>
</form>
multiple="mutiple"
옵션을 준다. ItemForm
의 다음 코드에서 여러 이미지 파일을 받을 수 있다.private List<MultipartFile> imageFiles;
상품명: <span th:text="${item.itemName}">상품명</span><br/>
첨부파일: <a th:if="${item.attachFile}" th:href="|/attach/${item.id}|"
th:text="${item.getAttachFile().getUploadFileName()}" /><br/>
<img th:each="imageFile : ${item.imageFiles}"
th:src="|/images/${imageFile.getStoreFileName()}|" width="300" height="300"/>
<img>
태그를 반복해서 출력.
많은 도움이 되었습니다, 감사합니다.