나중에 보기 위해 정리해둡니다
pom.xml에 코드 추가
<!-- 파일 업로드를 위해 추가함 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
servlet-context.xml에 코드 추가
<!-- 파일 업로드를 위해 추가함 -->
<beans:bean id="commonsMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="20971520"></beans:property> <!-- 최대 업로드 파일 크기 -->
<beans:property name="maxInMemorySize" value="10485760"></beans:property> <!-- 메모리에 최대로 저장할 수 있는 공간 -->
</beans:bean>
설정파일(root-context.xml)에 코드 추가
<!-- 파일 업로드를 위해 추가함 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
전송하려고 하는 폼에 enctype="multipart/form-data" 코드 추가
<form action="insertSang" enctype="multipart/form-data" method="post" name="frm">
파일에 type을 file이라고 지정
<tr>
<td>상품이미지</td>
<td><input type="file" name="file"></td>
</tr>
클래스에 MultipartHttpServletRequest mtfRequest, MultipartFile file, Model model 을 적어주고 코드를 복붙해서 넣기
sdto.setsImage에는 String 타입으로 파일명이 들어간다.
String path가 C드라이브의 image로 되어있기 때문에 image 폴더에 파일이 들어간다.
원하는 경로로 바꿔주면 된다.
@RequestMapping(value="insertSang", method=RequestMethod.POST)
public String insertSang2(
MultipartHttpServletRequest mtfRequest,
SangDto sdto,
MultipartFile file,
Model model) {
String src = mtfRequest.getParameter("src");
System.out.println("src value : " + src);
MultipartFile mf = mtfRequest.getFile("file");
String path = "C:\\image\\";
String originFileName = mf.getOriginalFilename(); // 원본 파일 명
long fileSize = mf.getSize(); // 파일 사이즈
System.out.println("originFileName : " + originFileName);
System.out.println("fileSize : " + fileSize);
String safeFile = path + System.currentTimeMillis() + originFileName;
try {
mf.transferTo(new File(safeFile));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//db에 넣기 위하여 적은 것임
sdto.setsImage(System.currentTimeMillis() + originFileName);
참고한 사이트 :
'언어 > Java' 카테고리의 다른 글
[Java] web.xml 파일 - 주소창에 index.jsp 안붙여도 나오게 설정 (0) | 2022.03.10 |
---|---|
[JSTL] c:forEach 2개의 값을 사용하는 방법 (0) | 2022.03.10 |
이클립스에 톰캣(tomcat) 서버 잡는 방법 (0) | 2022.03.10 |
톰캣(tomcat) 서버 설치방법 (0) | 2022.03.10 |
eclipse 설치방법 (0) | 2022.03.10 |
댓글