danbibibi
article thumbnail

1. pom.xml

Apache Commons FileUpload라이브러리를 이용하기 위해 dependency를 추가해준다! 

<html />
<!-- 파일 업로드 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.5</version> </dependency>

 

2. servlet-context.xml

file upload를 처리할 multipart resolver를 빈으로 등록해준다!

<html />
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <beans:property name="defaultEncoding" value="UTF-8"/> <!-- # 최대 업로드 가능한 파일의 바이트 크기 <beans:property name="maxUploadSize" value="52428800"/> # 디스크에 임시 파일을 생성하기 전에 메모리에 보관할 수 있는 최대 바이트 크기 <beans:property name="maxInMemorySize" value="1048576"/> --> </beans:bean>

 

3. regist.jsp

파일을 전송할 때는 enctype을 "multipart/form-data"로 설정해주어야 한다!

<html />
<form method="post" action="${root}/regist" enctype="multipart/form-data"> <fieldset> <legend>사용자 정보 입력</legend> <label for="id">아이디</label> <input type="text" id="id" name="id"><br> <label for="password">비밀번호</label> <input type="password" id="password" name="password"><br> <label for="name">이름</label> <input type="text" id="name" name="name"><br> <label for="email">이메일</label> <input type="email" id="email" name="email"><br> <label for="age">나이</label> <input type="number" id="age" name="age"><br> <div> <label for="file">이미지</label> <input type="file" id="file" name="file" class="input-image" accept="image/*" > </div> <input type="submit" value="등록"> <input type="reset" value="초기화"> </fieldset> </form>

 

4. MainController.java

controller에서 파일을 처리해주는 코드이다!

*resources/upload 폴더를 만들고, 안에 아무 파일이나 하나를 만들어 놓아야 인식 가능!!

<java />
@PostMapping("/regist") public String doRegist(@ModelAttribute User user, @RequestPart(required = false) MultipartFile file, Model model) throws IllegalStateException, IOException { if (file != null && file.getSize() > 0) { // 먼저 파일이 존재하는지 검사 // 파일을 저장할 위치 지정 Resource res = resLoader.getResource("resources/upload"); // 중복방지를 위해 파일 이름앞에 현재 시간 추가 user.setImg(System.currentTimeMillis() + "_" + file.getOriginalFilename()); // User 객체에 원본 파일 이름 저장 user.setOrgImg(file.getOriginalFilename()); // 파일 저장 file.transferTo(new File(res.getFile().getCanonicalPath() + "/" + user.getImg())); } // DB에 user 정보 등록 service.insert(user); return "/regist_result"; }

@RequestPart
- 메소드 파라미터가 웹 요청 파라미터에 바인딩되어야 함을 나타내는 annotation
- name-value 쌍의 form 필드와 함께 사용

@RequestParam

- “multipart/form-data” 요청의 일부를 메소드 파라미터와 연결하는 데 사용하는 annotation
- required = false 로 설정해 줄 경우, 꼭 받아오지 않아도 됨
- JSON, XML등을 포함하는 복잡한 내용의 Part와 함께 사용
- DTO에는 사용 불가 !

 

5. ServiceImpl

파일 업로드 경로를 설정하기 위해 ResourceLoader를 주입받는다!!

<java />
@Autowired ResourceLoader resLoader;

'WEB > back-end' 카테고리의 다른 글

Spring-MyBatis 실습  (0) 2023.04.24
MyBatis, MyBatis-Spring 설정  (0) 2023.04.24
Spring MVC 실습  (0) 2023.04.24
Interceptor  (0) 2023.04.22
AOP(Aspect Oriented Programming, 관점 지향 프로그래밍)  (0) 2023.04.22
profile

danbibibi

@danbibibi

꿈을 꾸는 시간은 멈춰 있는 것이 아냐 두려워하지 마 멈추지 마 푸른 꿈속으로