1. root-context.xml에 multipart-resolver 추가
<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000"></property>
</bean>
2. JSP
<form id="uploadForm" enctype="multipart/form-data">
<label id="applabel" class="col-sm-2 alert alert-info">Service Icon</label>
<div class="col-sm-4">
<input type="file" class="" id="file1" name="file" required="required">
</div>
<label id="applabel" class="col-sm-2 alert alert-info">Service Image</label>
<div class="col-sm-4">
<input type="file" class="" id="file2" name="file" required="required">
</div>
</form>
<button class="btn btn-primary pull-right" id="btn-upload">이미지업로드</button>
3.javascript
$('#btn-upload').on('click', function () {
if(($("#file1").val()==""||$("#file1").val()==null)){
alert("Service Icon이 없습니다.");
}else if(($("#file2").val()==""||$("#file2").val()==null)){ alert("Service Image가 없습니다."); }else{ var form = new FormData(document.getElementById('uploadForm')); $.ajax({ url: "/upload", //컨트롤러 URL data: form, dataType: 'text', processData: false, contentType: false, type: 'POST', success: function (response) { $("#progress1").css("width","100%"); $("#progress1").text("100%"); },error: function (jqXHR) { alert('error'); } }); } });
4. Controller
@RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public Object uploadFile(MultipartHttpServletRequest request ,HttpSession session) throws IOException { Iterator<String> itr = request.getFileNames(); if(itr.hasNext()) { List<MultipartFile> mpf = request.getFiles(itr.next()); //just temporary save file info into ufile for(int i=0; i< mpf.size();i++){ System.out.println("file length : " +mpf.get(i).getSize()); System.out.println("file name : " + mpf.get(i).getOriginalFilename() ); //String path = session.getServletContext().getRealPath("")+"/resources/catalog/image/"; String path ="/var/tomcat/webapps/soweb/resources/catalog/image/"; File files = new File(path + mpf.get(i).getOriginalFilename() ); mpf.get(i).transferTo(files); System.out.println(path); } return true; } else { return false; }
}