상세 컨텐츠

본문 제목

SpringMVC에서 MultipartFile 업로드

Programming/Spring Framework

by otamot 2012. 12. 18. 11:36

본문

SpringMVC에서 MultipartFile을 이용한 파일업로드 방법입니다.


1. 일단 jsp에서 <form> 태그 설정입니다.


 ...

<form:form method="POST" commandName="simpleUploadForm" enctype="multipart/form-data">
 ...

    <input type="file" name="file_nm1" />
</form:form>

 ...


enctype="multipart/form-data"으로 작성해야  multipart 객체로 받을 수 있습니다.


2. Context 환경 설정 내용입니다.


 ...

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>102400000</value>
</property>
</bean>

 ...


spring에서 사용할 수 있는 기본 MultipartResolver를 선언합니다.


3. Controller 부분 내용입니다.


 import org.springframework.web.multipart.commons.CommonsMultipartFile


...


@RequestMapping(value="/business/nondisRegisterPro.do")

public String nondisRegisterPro(MultipartHttpServletRequest request,  ModelMap model) throws Exception {


    Map<String, MultipartFile> files = request.getFileMap();

    CommonsMultipartFile cmf = (CommonsMultipartFile) files.get("file_nm1");

    String path ="c:/test/"+cmf.getOriginalFilename();


    File f = new File(path);

    // 파일 업로드 처리 완료.

    cmf.transferTo(f);


    HashMap map = new HashMap();

    map.put("edu_inddis_no", request.getParameter("edu_inddis_no"));

    

    try {

        minwonService.nondisInsert(map);

        model.addAttribute("resMessage", "성공적으로 신청되었습니다."); 


    } catch (Exception e) {


        model.addAttribute("resMessage", "등록중 오류가 발생하였습니다"); 

    }

    

    return "www/business/nondisRegister";

}


jsp의 file 객체명 'file_nm1'으로  CommonsMultipartFile 객체를 받고 transferTo(...) method를 이용해서 원하는 path로 파일을 떨어뜨리면 됩니다. transferTo method가 참 유용합니다. 없었다면 stream 객체를 이용해서 구현해야 했는데 말이죠.



관련글 더보기