728x90
[파일 업로드]
파일 업로드를 위해서는 다음과 같은 설정들이 필요하다.
1. VIEW
파일을 업로드하는 form 태그에 enctype="multipart/form-data"를 추가한다.
<form action="insertBoard.do" method="post" enctype="multipart/form-data">
2. Command 객체(bVO)
정보를 받는 bVO 객체에 변수를 추가해 준다.
private MultipartFile uploadFile; // 멀티파일 객체
3. Fileupload 라이브러리(.jar) 추가 -> pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
4. MultipartResolver 설정 -> DispatcherServlet-servlet.xml
<!-- 파일 업로드 관련 설정 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
</bean>
이미지 업로드 수행 순서
1) VIEW --데이터 전송-->> Command 객체에 세팅(bvo.setMF)
(이 과정에서 내부적으로 new MultipartFile(); 해야 하므로 객체 생성을 스프링 컨테이너가 관리한다.)
2) 업로드한 파일 존재여부 확인
3) 업로드한 파일을 지정한 경로에 저장
4) 업로드한 파일명 세팅
@RequestMapping("/insertBoard.do")
public String insertBoard(BoardVO bVO) throws IllegalStateException, IOException {
MultipartFile uploadFile = bVO.getUploadFile();
if(!uploadFile.isEmpty()) { // 업로드한 파일 존재여부 확인
String fileName=uploadFile.getOriginalFilename(); // 업로드한 파일명
uploadFile.transferTo(new File("C:\\Users\\Administrator\\git\\spring-day08\\test\\src\\main\\webapp\\images\\"+fileName));
// 업로드한 파일을 지정한 경로에 저장
System.out.println(fileName);
bVO.setImg(fileName); // 업로드한 파일명 세팅
}
boardService.insertBoard(bVO);
return "redirect:main.do";
}
728x90
'Spring' 카테고리의 다른 글
Spring 다국어 처리 (0) | 2022.09.29 |
---|---|
Spring 예외 페이지 설정 (0) | 2022.09.28 |
2-Layered 아키텍처 (0) | 2022.09.26 |
Spring 다양한 @(어노테이션) 설정 (0) | 2022.09.23 |
Spring MVC2 .xml 설정 어노테이션으로 변경 (0) | 2022.09.22 |