分享:js上传文件的类

发布时间:2020-04-08编辑:脚本学堂
本文分享一个 javascript 实现的上传文件的类,另一种文件上传与检测的思路,有需要的朋友参考学习下。

js文件上传类一例,代码如下:
 

复制代码 代码示例:
<script>
/**
* js 上传文件的类
* by www.jb200.com
*/
var jsUpload = new function(){ 
    this.hiddenFrameId = 'js_upload_frame'; 
    this.uploadCallBack; 
    this.getHiddenFrame = function(){ 
        if(this.loginWin==null){ 
            this.loginWin=document.getElementById(this.hiddenFrameId); 
        } 
        if(this.loginWin==null){ 
            var div=document.createElement("div"); 
            div.id="material_upload_frame_container"; 
            div.style.display="none"; 
            document.body.appendChild(div); 
            var frameHtml='<iframe name="'+this.hiddenFrameId+'" id="'+this.hiddenFrameId+'" '; 
            frameHtml+='width=0 height=0 style="display:none;" onload="jsUpload.frameCallback()"></iframe>'; 
            div.innerHTML=frameHtml; 
            this.loginWin=document.getElementById(this.hiddenFrameId); 
        } 
        return this.loginWin 
    } 
    this.frameCallback = function(json){ 
        var logWin=document.getElementById(this.hiddenFrameId),response=""; 
        if(json){ 
            response=json 
        }else{ 
            try{ 
                response=logWin.contentWindow.document.body.innerHTML 
            }catch(e){ 
                location.reload() 
            } 
        } 
        if(response!=""&&response.length<6000){ 
            pos1=response.indexOf("{"); 
            pos2=response.lastIndexOf("}"); 
            if(pos1>=0&&pos2>0){ 
                response=response.substring(pos1,pos2+1) 
            }else{ 
                response="{}" 
            } 
            var result={},param={}; 
            response=response.replace(/r/g,"").replace(/n/g,""); 
            try{ 
                eval("result="+response) 
            }catch(e){ 
            } 
            if (typeof this.uploadCallBack=='function') { 
                this.uploadCallBack(result); 
            } else { 
                if(result['errno']!=0){ 
                    alert(result['errmsg']); 
                } 
            } 
        } 
    } 
    this.setUploadCallBack = function(func){ 
        this.uploadCallBack = func; 
    } 
    this.upload = function(form, callback){ 
        if (typeof callback=='function'){ 
            this.setUploadCallBack(callback); 
        } 
        this.getHiddenFrame(); 
        form.target = this.hiddenFrameId; 
        form.submit(); 
    } 
};</script>