关于ajaxfileupload.js一些问题和上传图片就立即显示图片功能

  ajaxfileupload.js是上传文件的一个插件,最近碰到的一个问题是在谷歌浏览器上传文件之后,原文本框中的文件名称消失,网上搜了好长时间也没有十分满意的答案。无刷新上传文件我想到的只有ajax,ajaxfileupload.js插件非常简单,看个简单例子就会使用,不用明白js里面写的到底是什么。流程就是就是先利用jQuery的选择器获得file文件上传框中的文件路径值,然后js就会动态的创建一个iframe和表单,并在里面建立一个新的file 文件框,提供post方式提交到后台。最后,返回结果到前台。

  我的功能需求是在选中图片的时候就自动上传图片,并且可以马上显示,刚做的时候没有想到上传图片,用了一个onchange函数可以让上传的图片显示出来,之后提交之前有一个预览功能,之前的上传的图片还要展现出来,这个时候才想起来把图片先存放某一个地方,这样连上传即展现的功能也能解决。不过为了以后会用到这个功能我就和上传图片的一起写出来。

html上传文件的

 1 <script type="text/javascript" src='/Public/js/jquery-1.4.2.min.js'></script>
 2 <!--上传图片的JS 修改之后的-->
 3 <script charset="utf-8" src="/Public/js/ajaxfileupload_modify.js"></script>
 4 <script type="text/javascript">
 5 //图片展示和删除  其他函数是选中图片下面就会展现出来图片的相关函数
 6 function onUploadImgChange(sender,img,obj){  
 7     if( !sender.value.match( /.jpg|.gif|.png|.bmp|.jpeg/i ) ){        
 8         alert('图片格式无效!');   
 9         return false;       
10     }                    
11     var objPreview = document.getElementById(obj);        
12     var file=document.getElementById(img);
13     if( sender.files &&  sender.files[0] ){ 
14         objPreview.style.display = 'block';        
15         objPreview.style.width = 'auto';        
16         objPreview.style.height = 'auto';
17         objPreview.src = window.URL.createObjectURL(file.files[0]);
18     }  
19     //上传到服务器图片方便预览 这一块是选中图片即上传
20     $.ajaxFileUpload ({
21         url:'__URL__/page_preview', //你处理上传文件的服务端
22         secureuri:false, //与页面处理代码中file相对应的ID值
23         fileElementId:'btn_pic',
24         dataType: 'json', //返回数据类型:text,xml,json,html,scritp,jsonp五种
25         success: function (data) 
26         {
27             if(data.file_infor ==1 )
28             {
29                 //存放的地址展示出来
30                 $("#tmp_btn_pic").val(data.file_url);
31             }
32         }
33     })
34 }        
35 
36 function onPreviewLoad(sender){
37     autoSizePreview( sender, sender.offsetWidth, sender.offsetHeight );      
38 }
39 
40 function autoSizePreview( objPre, originalWidth, originalHeight ){     
41     var zoomParam = clacImgZoomParam( 300, 300, originalWidth, originalHeight );        
42     objPre.style.width = zoomParam.width + 'px';        
43     objPre.style.height = zoomParam.height + 'px';        
44     objPre.style.marginTop = zoomParam.top + 'px';        
45     objPre.style.marginLeft = zoomParam.left + 'px';        
46 }        
47 
48 function clacImgZoomParam( maxWidth, maxHeight, width, height ){        
49     var param = { width, height:height, top:0, left:0 };        
50     if( width>maxWidth || height>maxHeight ){        
51         rateWidth = width / maxWidth;        
52         rateHeight = height / maxHeight;        
53         if( rateWidth > rateHeight ){        
54             param.width =  maxWidth;        
55             param.height = height / rateWidth;        
56         }else{        
57             param.width = width / rateHeight;        
58             param.height = maxHeight;        
59         }        
60     }        
61     param.left = (maxWidth - param.width) / 2;        
62     param.top = (maxHeight - param.height) / 2;              
63     return param;        
64 }
65 
66 function del_img(obj,div){
67     if(confirm("确定要删除此图片?"))
68     {
69         $('#'+obj+'').val('');
70         objPreview = document.getElementById(div);
71         objPreview.style.display = 'none';
72     }else{
73         return false;
74     }
75 }
76 </script>
77 <input type="file" name="btn_pic" id="btn_pic" onchange="onUploadImgChange(this,'btn_pic','preview2');" />
78 <div>
79     <img id="preview2" onload="onPreviewLoad(this)"/>
80 </div>
81 <input type="button" value="删除" onclick="del_img('btn_pic','preview2');" />

php后台处理

 function page_preview() 
{//出来ajaxupload的图片
        //如果有按钮图片先存放某个地方
        $folder = "/img/" . date("Ym/d/");
        $this->mkDirs(UPLOAD_PATH . $folder);
        $path = $folder . time() . rand(1000,9999) . $_FILES['btn_pic']['name'];
        $img_path = UPLOAD_PATH . $path;
        $ok=@move_uploaded_file($_FILES['btn_pic']['tmp_name'],$img_path);
        if($ok === FALSE)
        {
            $file_infor = 0;
            echo '{"file_infor":"' . $file_infor .'"}';
        }else
        {
            $file_infor = 1;
            echo '{"file_infor":"' . $file_infor . '","file_url":"' . $path . '"}';
        }
 }

 在原来的ajaxfileupload.js中修改了一下就可以传完之后原来的文本框的值不会丢失。这也是从网上搜集来的我总结一下

jQuery.extend({

    createUploadIframe: function(id, uri)
    {
            //create frame
            var frameId = 'jUploadFrame' + id;
            
            if(window.ActiveXObject) {  
                if(jQuery.browser.version=="9.0" || jQuery.browser.version=="10.0"){  
                        var io = document.createElement('iframe');  
                        io.id = frameId;  
                        io.name = frameId;  
                 }else if(jQuery.browser.version=="6.0" || jQuery.browser.version=="7.0" || jQuery.browser.version=="8.0"){  
                        var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');  
                        if(typeof uri== 'boolean'){  
                            io.src = 'javascript:false';  
                        }  
                        else if(typeof uri== 'string'){  
                            io.src = uri;  
                        }  
                    }  
                }  else {
                var io = document.createElement('iframe');
                io.id = frameId;
                io.name = frameId;
            }
            io.style.position = 'absolute';
            io.style.top = '-1000px';
            io.style.left = '-1000px';

            document.body.appendChild(io);

            return io            
    },
    createUploadForm: function(id, fileElementId)
    {
        //create form    
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');    
        var oldElement = $('#' + fileElementId);
        var newElement = $(oldElement).clone();
        $(oldElement).attr('id', fileId);
        $(oldElement).before(newElement);
        $(oldElement).appendTo(form);
        //set attributes
        $(form).css('position', 'absolute');
        $(form).css('top', '-1200px');
        $(form).css('left', '-1200px');
        $(form).appendTo('body');        
        return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout    
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = s.fileElementId;        
        var form = jQuery.createUploadForm(id, s.fileElementId);
        var io = jQuery.createUploadIframe(id, s.secureuri);
        var frameId = 'jUploadFrame' + id;
        var formId = 'jUploadForm' + id;

        // Watch for a new set of requests
        if (s.global && ! jQuery.active++)
        {
            jQuery.event.trigger("ajaxStart");
        }   
         
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back

        var uploadCallback = function(isTimeout)
        {            
            var io = document.getElementById(frameId);
            try 
            {                
                if(io.contentWindow)
                {
                     xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                     xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
                     
                }else if(io.contentDocument)
                {
                     xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                    xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
                }                        
            }catch(e)
            {
                jQuery.handleError(s, xml, null, e);
            }
      
            if ( xml || isTimeout == "timeout") 
            {                
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
                    {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData(xml, s.dataType);    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger("ajaxSuccess", [xml, s]);
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
                {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if(s.global)
                    jQuery.event.trigger("ajaxComplete", [xml, s]);

                // Handle the global AJAX counter
                if (s.global && ! --jQuery.active)
                    jQuery.event.trigger("ajaxStop");

                // Process result
                if (s.complete)
                    s.complete(xml, status);

                jQuery(io).unbind();

                setTimeout(function()
                                    {    try 
                                        {
                                            $(io).remove();
                          //修改的
                                            var fileElementId = 'jUploadFile' + id;
                                            var oldElement = $('#' + fileElementId);
                                            var newElement = $('#' + id);
                                            $(newElement).after(oldElement);
                                            $(newElement).remove();
                                            $(oldElement).attr('id', id);
                          //结束
                                            $(form).remove();    
                                            
                                        } catch(e) 
                                        {
                                            jQuery.handleError(s, xml, null, e);
                                        }                                    

                                    }, 100)

                xml = null

            }
        }
        // Timeout checker
        if (s.timeout > 0) 
        {
            setTimeout(function(){
                // Check to see if the request is still happening
                if(!requestDone ) uploadCallback("timeout");
            }, s.timeout);
        }
        try 
        {
           // var io = $('#' + frameId);
            var form = $('#' + formId);
            $(form).attr('action', s.url);
            $(form).attr('method', 'POST');
            $(form).attr('target', frameId);
            if(form.encoding)
            {
                form.encoding = 'multipart/form-data';                
            }
            else
            {                
                form.enctype = 'multipart/form-data';
            }            
            $(form).submit();

        } catch(e) 
        {            
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        }         
        return {abort: function () {}};    

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if (type == "script")
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if (type == "json")
            eval( "data = " + data );
        // evaluate scripts within html
        if (type == "html")
            jQuery("<div>").html(data).evalScripts();
            //alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
})

这样就解决了ajax上传之后 原本文本框丢失的问题。

图片上传就显示,我们需要了解Javascript里File对象、Blob对象和window.URL.createObjectURL()方法。上面所写的html中已经有了立即显示的代码

以后可以研究研究其中的机制。

所有这些我只是写出来解决的方法,但是具体的原理还不是很懂。欢迎大家吐槽和评论!

   

原文地址:https://www.cnblogs.com/angellating/p/4936154.html