仅需要new一个对象,将上传后台的url和点击触发上传的元素id传给对象,就可以自从实现上传

暂不支持IE

 1 <html>  
 2 <body>  
 3 <a href="#" id="a_upload">上传</a>
 4 </body>  
 5 </html>  
 6 <script src="lib_shb_fileupload.js"></script>   
 7 <script type="text/javascript">  
 8 var fu = new SHBFileUpload("doUpload.jsp",'a_upload');
 9 fu.callback = function(){
10     console.log(fu.status) ;
11     console.log(fu.responseText) ;
12 }
13 </script>  

js源码如下:

 1 /**
 2 *简单的文件上传
 3 *@author:索洪波
 4 *@qq:609690891
 5 *@version:1.0
 6 */
 7 /**
 8 *@SHBFileUpload
 9 *@param:url上传url
10 *@param:id 出发上传操作的元素id
11 */
12 
13 function SHBFileUpload(url,id){
14     this.url = url ;
15     this.id = id ;
16     this.iframe  = null ;
17     this.form = null ;
18     this.input = null ;
19     this.status = 'init' ;
20     this.responseText = '' ;
21     this.timeout = 100 ;
22 
23     this.init();
24 }
25 SHBFileUpload.prototype.createIframe = function(){
26     var iframe = document.createElement('iframe') ;
27     iframe.id = 'SHB_FU_Frame' ;
28     iframe.name = 'SHB_FU_Frame' ;
29     iframe.style.display = 'none' ;
30     document.body.appendChild(iframe);
31     this.iframe = iframe ;
32 }
33 SHBFileUpload.prototype.createForm = function(){
34     var form = document.createElement('form') ;
35     form.action = this.url ;
36     form.id = 'SHB_FU_Form' ;
37     form.name = 'SHB_FU_Form' ;
38     form.method = 'post' ;
39     form.encoding = 'multipart/form-data' ;
40     form.target = 'SHB_FU_Frame' ;
41     form.style.display = 'none' ;
42     this.form = form ;
43 
44     var input = document.createElement('input') ;
45     input.type = 'file' ;
46     input.id = 'SHB_FU_Input' ;
47     input.name = 'SHB_FU_Input' ;
48     input.style.display = 'none' ;
49     var self = this ;
50     input.onchange = function(){self.doUpload()} ;
51     this.input = input ;
52 
53     form.appendChild(input) ;
54     document.body.appendChild(form) ;
55 }
56 SHBFileUpload.prototype.doUpload = function(){
57     this.status = 'sending' ;
58     var self = this ;
59     this.iframe.onload = function(){self.hasLoad()} ;
60     this.form.submit();
61 }
62 SHBFileUpload.prototype.init = function(){
63     this.createIframe() ;
64     this.createForm() ;
65     var self = this ;
66     document.getElementById(this.id).onclick = function(){self.input.click()} ;
67 }
68 SHBFileUpload.prototype.hasLoad = function(){
69     var iframe = this.iframe ;
70     this.status = 'success' ;
71     if(iframe.contentWindow){
72          this.responseText = iframe.contentWindow.document.body?iframe.contentWindow.document.body.innerHTML:"";
73     }else if(iframe.contentDocument){
74          this.responseText = iframe.contentDocument.document.body?iframe.contentDocument.document.body.innerHTML:"";
75     }
76     this.callback() ;
77 }
78 SHBFileUpload.prototype.callback = function(){}