본문 바로가기
언어/Java

[Spring] 스프링 MVC 단일 파일 업로드 방법

by 만_두 2022. 3. 10.

나중에 보기 위해 정리해둡니다

 

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);

참고한 사이트 :

https://kitty-geno.tistory.com/102

https://ktko.tistory.com/129

https://m.blog.naver.com/javaking75/140203390797

댓글