회원가입+프로필사진
설정
pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
servlet-context.xml
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="defaultEncoding" value="UTF-8"/>
<beans:property name="maxUploadSize" value="10000000"/>
<beans:property name="maxUploadSizePerFile" value="5000000"></beans:property>
</beans:bean>
뷰
join.jsp
<body>
<h1>회원가입</h1>
<form action="join" method="post" enctype="multipart/form-data">
아이디 : <input type="text" name="id"><br>
비밀번호 : <input type="password" name="pwd"><br>
닉네임 : <input type="text" name="nick"><br>
프로필 사진 : <input type="file" name="profileList" multiple accept=".jpg, .png"><br>
<input type="submit" value="가입하기">
</form>
</body>
VO
MemberVo
public class MemberVo {
private String id;
private String pwd;
private String nick;
private List<MultipartFile> profileList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public List<MultipartFile> getProfileList() {
return profileList;
}
public void setProfileList(List<MultipartFile> profileList) {
this.profileList = profileList;
}
public boolean isFileOk() {
if(profileList.get(0).isEmpty() || profileList.size() < 1 || profileList == null || profileList.get(0) == null) {
return false;
}
return true;
}
@Override
public String toString() {
return "MemberVo [id=" + id + ", pwd=" + pwd + ", nick=" + nick + ", profileList=" + profileList + "]";
}
}
컨트롤러
MemberController
import com.kh.app16.member.vo.MemberVo;
@Controller
@RequestMapping("member")
public class MemberController {
@GetMapping("join")
public String join() {
return "member/join";
}
@PostMapping("join")
public String join(MemberVo m) throws IllegalStateException, IOException {
List<MultipartFile> list = m.getProfileList();
if(m.isFileOk()) {
return "redirect:/errorPage";
}
System.out.println("size: "+ list.size());
System.out.println("첫번째 파일이 비어있나요? "+list.get(0).isEmpty());
for(MultipartFile p : list) {
System.out.println("=======");
System.out.println("p: "+p);
System.out.println("p파일비어있나요? "+ p.isEmpty());
System.out.println("p 이름: "+p.getOriginalFilename());
System.out.println("p 크기: "+p.getSize());
System.out.println("p 타입: "+p.getContentType());
File file = new File("D:\\uploadForSpring", p.getOriginalFilename());
p.transferTo(file);
}
return "redirect:/";
}
}
파일이 비어있으면?
- 객체가 존재하므로
size() == 1
이다.
- 파일업로드 여부 ==
isEmpty()
로 확인하자!