Spring Ajax File upload
1.jsp file 중 전송부분
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//버튼 클릭시 $("#btn_file_reg").click(function() { var form = $('form')[0]; var formData = new FormData(form); $.ajax({ url: 'fileuploadAjax.ajax', type: 'POST', data:formData, contentType: false, processData: false, success: function(data){ alert('업로드 성공'); }, error: function(e){ alert(e.reponseText); } }); }); |
2.Java Controller 부분
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
@RequestMapping(value = "fileuploadAjax",method = RequestMethod.POST) public void fileuploadAjax(@RequestParam("btn_file") MultipartFile fileupload, Model model) { String ofn = fileupload.getOriginalFilename(); System.out.println("File_size : " + fileupload.getSize()); System.out.println("File_ext : " + ofn.indexOf(".") > -1 ? ofn.substring(ofn.lastIndexOf(".") + 1) : ""); System.out.println("File_name : " + ofn); InputStream stream = null; OutputStream bos = null; UUID uuid = UUID.randomUUID(); String tempFileName uuid.toString(); String realPath = "/fileupload"; try { stream = fileupload.getInputStream(); bos = new FileOutputStream(realPath + "/" + tempFileName); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.close(); stream.close(); l.info("The file has been written to [{}]", tempFileName); } catch (FileNotFoundException e) { e.printStackTrace(); if (stream != null) try { stream.close(); stream = null; } catch (Exception localException) { } if (bos != null) try { bos.close(); bos = null; } catch (Exception localException1) { } } catch (IOException e) { e.printStackTrace(); if (stream != null) try { stream.close(); stream = null; } catch (Exception localException2) { } if (bos != null) try { bos.close(); bos = null; } catch (Exception localException3) { } } finally { if (stream != null) try { stream.close(); stream = null; } catch (Exception localException4) { } if (bos != null) try { bos.close(); bos = null; } catch (Exception localException5) { } } } |
3.Spring xml 설정중
1 2 3 4 5 6 |
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>10000000</value> </property> </bean> |