ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [파일업로드] 서버에서의 처리
    파일업로드 2016. 9. 12. 14:25

    <form> 이나 Ajax 방식으로 클라이언트에서 서버로 파일을 전송하는 방법을 살펴봤다. 이를 서버에서 받으려면 몇가지 설정과 코드가 필요하다.

     

     

    파일 업로드를 위한 라이브러리를 추가한다.

     

    pom.xml

    1
    2
    3
    4
    5
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.1</version>
            </dependency>
    cs

     

     

    context 에 multipart 로 들어오는 데이터 처리를 위한 설정을 추가한다. 이는 servlet-context 에 추가하면 되는데, 없다면 root-context 에 추가한다.

     

    servlet-context.xml

    1
    2
    3
    4
        <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 10MB -->
            <beans:property name="maxUploadSize" value="10485760"></beans:property>
        </beans:bean>
    cs

     

     

    한글 파일 이름 처리를 위해 filter 를 추가한다.

     

    web.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
        <filter>
            <filter-name>encoding</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        </filter>
        
        <filter-mapping>
            <filter-name>encoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    cs

     

     

    이후 Controller 에서 아래와 같이 handler 를 만들면 파일을 받을 수 있다. MultipartFile class 로 받은 file 의 정보를 여러 메서드를 호출하여 확인할 수 있다. 이후에는 목적에 맞춰 개발하면 된다.

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
        @RequestMapping(value = "/uploadForm", method = RequestMethod.POST)
        public String uploadForm(MultipartFile file, Model model) throws Exception {
            
            logger.info("originalName: " + file.getOriginalFilename());
            logger.info("size: " + file.getSize());
            logger.info("contentType: " + file.getContentType());
            
            String savedName = uploadFile(file.getOriginalFilename(), file.getBytes());
            
            model.addAttribute("savedName", savedName);
            
            return "uploadResult";
        }
    cs

     

     

    포스팅하는 주요 내용들은 "코드로 배우는 스프링 웹 프로젝트" 란 책에 있는 내용을 실습하면서 공부한 내용이다. 개인적으로 현시점에서 초보자가 보기에 가장 좋은 책이 아닌가 한다. 이론 위주가 아닌, 실무에서 필요한 기술의 사용방법이 주인 책이다. 첨부는 실습해보면서 작성한 프로젝트로, 책에 있는 실제 예제는 남가람북스에서 다운 받을 수 있다. (가람북스 자료실이나 네이버카페)

     

    업로드 프로젝트 전체 : 

    upload.zip
    다운로드

     

    실제 프로젝트에서는 업로드 뿐 아니라 이미지의 스케일링 작업도 하고 있어 몇가지 설정을 더 해줘야 한다.

    '파일업로드' 카테고리의 다른 글

    [파일업로드] 업로드한 파일 다운로드 처리  (0) 2016.09.12
    [파일업로드] Ajax 방식  (3) 2016.09.11
    [파일업로드] <form> 방식  (0) 2016.09.11
    [파일업로드] MIME  (0) 2016.09.10
Designed by Tistory.