출처 : http://blog.naver.com/sh_park0107/130175661601


* 화면전환 없이 비동기 업로드 *


1. 파일 업로드 폼

/fileUpload.jsp

 

1
2
3
4

<form name="serverInfoForm" id="serverInfoForm" method="post" action="/serverInfoUpload.do" enctype = "multipart/form-data">

        <input type="file" name="agentInstallFile" id="agentInstallFile"> 

        <input type="submit"  class="btn" value="전송">
</form>

 

  • form 의 id 를 지정해준다.
  • action 을 지정해준다. 파일을 보내는 컨트롤러
  • enctype을 반드시 multipart/form-data로 지정해준다.

 

2jquery.form.js 플러그인 사용하기

 

  • http://malsup.com/jquery/form/#download 에서 jquery.form.js 혹은 jquery.form.min.js 다운을 받아 js폴더에 넣어준다.
  •  <script src="js/jquery.form.js"></script> ㅎㅔ더(<HEAD></HEAD>에 삽입해준다

 

 

3. 파일업로드 jquery 소스 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$('#serverInfoForm').ajaxForm({
        
        dataType : 'text', 
        beforeSerialize: function(){
             // form을 직렬화하기전 엘레먼트의 속성을 수정할 수도 있다.            
        },
        beforeSubmit : function() {
        //action에 걸어주었던 링크로 가기전에 실행 ex)로딩중 표시를 넣을수도 있다.
        },

        success : function(data) {
             //컨트롤러 실행 후 성공시 넘어옴
            alert("등록완료 ! ");            
        }

    });

http://malsup.com/jquery/form/ 참고 ! (API)

 

 

  • form id를 넣어준다. $("#serverInfoForm")
  • beforeSerialize 는 form 을 직렬화 하기전에 실행되는 함수이다.
  • beforeSubmit 는 form 이 submit 되기전에 실행되는 함수

 

4. 파일업로드 컨트롤러 

MultipartHttpServletRequest 를 사용하기위 엮인글의 1번과, 3번 설정 필요!!

역인글 :  http://blog.naver.com/sh_park0107/130175605306


/serverInfoUpload.do

 Colored By Color Scripter

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
@RequestMapping("/serverInfoUpload.do")
    public ModelAndView mybatistest(HttpServletRequest request) throws IOException{

        ModelAndView mav = new ModelAndView();
        
        MultipartHttpServletRequest multi = (MultipartHttpServletRequest) request;
        MultipartFile file = multi.getFile("agentInstallFile");//jsp 페이지에서 input type="file"의 파라미터명
                
         String path="";
         UUID randomeUUID = UUID.randomUUID();//중복 파일명 방지
                  
         if(file!=null){
        
          System.out.println("파라미터명" + file.getName());
          System.out.println("파일크기" + file.getSize());
          System.out.println("파일 존재" + file.isEmpty());
          System.out.println("오리지날 파일 이름" + file.getOriginalFilename());
        
          
          path = "d:/upload/";
          InputStream inputStream = null;
          OutputStream outputStream = null;
          
          String organizedfilePath="";
          
          try {
              
 
              if (file.getSize() > 0) {
                  inputStream = file.getInputStream();
                  File realUploadDir = new File(path);
                  
                  if (!realUploadDir.exists()) {//업로드하려는 path에 폴더가 없을경우
                      realUploadDir.mkdirs();//폴더생성.
                  }
                  
                  
                  organizedfilePath = path + randomeUUID + "_" + file.getOriginalFilename();
                  System.out.println(organizedfilePath);//파일이 저장된경로 + 파일 명
                  
                  outputStream = new FileOutputStream(organizedfilePath);
 
                  int readByte = 0;
                  byte[] buffer = new byte[8192];
 
                  while ((readByte = inputStream.read(buffer, 0, 8120)) != -1) {
                      outputStream.write(buffer, 0, readByte); //파일 생성 ! 
                      
                  }
            
                  
              }
              
          } catch (Exception e) {
              // TODO: handle exception
              e.printStackTrace();
 
          } finally {
 
              outputStream.close();
              inputStream.close();
          }
          
      
                 
         }    
          mav.setViewName("fileUpload");
        return mav;
                
    }

 


'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

JSP SQL Injection 방어 기법  (0) 2014.08.21
JSP 버튼이벤트  (0) 2014.08.19
JSP Modal 사용하기  (0) 2014.08.14
JSP c:choose  (0) 2014.08.14
JSP select onchange  (0) 2014.08.14

+ Recent posts