Spring/Spring Framework
[Spring] Spring 파일업로드 & Postman 파일업로드 테스트
soom2628
2022. 10. 4. 15:00
1. 환경
Spring Framework
tomcat 8.5
Postman 9.31.0
2. 세팅
1) pom.xml
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2) web.xml
<filter>
<filter-name>MultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3) bean 등록
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000000" />
<property name="maxInMemorySize" value="100000000" />
</bean>
나는 dispatcher-servlet.xml 에 추가했다.
환경에 따라 다를 수 있음!
4) context.xml
<Context allowCasualMultipartParsing="true" path="/">
<!-- Default set of monitored resources. If one of these changes, the -->
<!-- web application will be reloaded. -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
</Context>
allowCasualMultipartParsing="true" path="/" 를 추가해줘야 한다.
1~3번 설정하고 다른 사람들꺼 코드 복붙해도 오류가 와장창 나서 뭔가.. 했는데
저걸 추가 했더니 깔끔하게 실행됐다ㅎㅎ
3. 소스
@RequestMapping(value = "/fileUpload.do" )
@ResponseBody
public ResultVo fileUpload(MultipartFile file, HttpServletResponse response) {
ResultVo result = new ResultVo();
try {
Map<String, String> dataMap = new HashMap<>();
dataMap.put("ContentType", file.getContentType());
dataMap.put("OriginalFilename", file.getOriginalFilename());
dataMap.put("Size", String.valueOf(file.getSize()));
result.setData(dataMap);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return result;
}
url 호출시 key값을 file로 보내기 때문에 @RequestParam("file")은 생략 가능하다.
4. Postman 파일 업로드 테스트
1) Body 선택
2) form-data 선택
3) KEY값 입력 창 오른쪽 콤보박스 선택
4) File 선택
5) Select Files를 눌러 업로드 할 파일 선택
❗ POST 방식으로 호출했습니다.
정상 호출 확인 끝~
+ 추가(PostMan 에러)
파일이 너의 디렉토리에 없다는 솰라솰라~
파일이 포스트맨에서 설정한 디렉토리에 없어서 나는 오류다
근데 그냥 호출해도 잘만 되긴 한다;;
그치만 그냥 오류가 보기 싫으니까,, 해결해야지!
1) Postman 오른쪽 상단 프로핑 옆옆에 톱니바퀴 버튼(설정 버튼. Settings)
2) SETTINGS > General
3) Location에 지정되어있는 폴더에 파일이 있어야만 오류 메시지가 안 뜬다