개발에 AtoZ까지

[Spring] 파일 단일/다중 업로드(Multipart) 본문

백엔드/Spring

[Spring] 파일 단일/다중 업로드(Multipart)

AtoZ 개발자 2021. 1. 23. 18:52
반응형

Spring 환경에서의 파일 업로드 방법에 대해 공유드립니다.

1. POM.xml

파일업로드를 위해 maven에 파일업로드 라이브러리 추가

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3</version>
</dependency>

2. web.xml

Spring Security와 Multipart 사용시에는 Multipart 필터를 Spring Security 앞에 설정해줘야한다.

안그러면 Multipart 필터가 정상적으로 동작하지 않는 현상 발생

    <filter>
        <description>스프링 파일업로드 필터 등록-스프링시큐리티설정전에 위치해야 한다</description>
        <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>*.do</url-pattern>
    </filter-mapping>
    <filter>
        <description>스프링 시큐리티 필터 등록</description>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>

3. servlet-context.xml

CommonsMultipartResolver bean 등록, CommonsMultipartResolver 옵션은 아래와 같다.

Property Type Description
maxUploadSize Long 최대 업로드 가능한 바이트 크기, -1은 제한이 없음을 의미합니다. Default(-1)
maxInMemorySize int 디스크에 임시 파일을 생성하기 전에 메모리에 보관할 수 있는 최대 바이트 크기, 기본 값은 10240 바이트입니다.
defaultEncording String 요청을 파싱할 때 사용할 캐릭터 인코딩, 지정하지 않은 경우 HttpServletRequest.setEncording() 메서드로 지정한 캐릭터 셋이 사용됩니다. 아무 값도 없을 경우 ISO-8859-1을 사용합니다.
<!--파일업로드 설정(multiparts)  -->
<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"/>
<!-- 파일업로드 크기 20MB로 설정 -->
    <property name="maxUploadSize" value="209715200"/>
</bean>

4. WAS 설정(context.xml)

WAS(Tomcat)/ config/context.xml에 <context>에 아래와 같이 변경한다. 

만약 WAS에 아래와 같이 설정하지 않으면 "Could not parse multipart servlet request" 에러발생,  WAS에서 Multipart를 찾지 못하게 된다.

<Context allowCasualMultipartParsing="true" >

 

5. JSP 소스

1) 단일 파일 

Multipart 사용시에는 enctype="multipart/form-data" 속성을 사용해줘야 한다.

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>파일업로드</title>
</head>
<body>
    <form name="fileForm" action="fileupload1" method="post" enctype="multipart/form-data">
    <sec:csrfInput/>
        <input type="file" name="file" />
        <input type="submit" value="전송" />
    </form>
</body>
</html>

 

 

2) 다중 파일

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>파일업로드</title>
</head>
<body>
    <form name="fileForm" action="fileupload1" method="post" enctype="multipart/form-data">
    <sec:csrfInput/>
        <input multiple="multiple"  type="file" name="picFile" required="required">
        <input type="submit" value="전송" />
    </form>
</body>
</html>

6. Controller 소스

1) 단일파일

 @RequestMapping(value = "fileupload1")
    public String requestupload1(MultipartHttpServletRequest mRequest) {
        String src = mRequest.getParameter("src");
        MultipartFile mf = mRequest.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 + 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();
        }

        return "redirect:/";
    }

2) 다중파일

@RequestMapping(value = "fileupload2")
    public String requestupload2(MultipartHttpServletRequest mRequest) {
        List<MultipartFile> fileList = mRequest.getFiles("file");
        String src = mRequest.getParameter("src");

        String path = "C:\\image\\";

        for (MultipartFile mf : fileList) {
            String originFileName = mf.getOriginalFilename(); // 원본 파일 명
            long fileSize = mf.getSize(); // 파일 사이즈

            System.out.println("originFileName : " + originFileName);
            System.out.println("fileSize : " + fileSize);

            String safeFile = path + 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();
            }
        }

        return "redirect:/";
    }
반응형
Comments