zoukankan      html  css  js  c++  java
  • Ajax引用 ajaxfileupload.js 进行文件上传

    第一次写博客还真有点激动中带有意思彷徨,哈哈哈 有什么不足的请多多指教

    这个应该是我目前用过的除了框架之外最好用的文件上传 ”工具“ 了,不说废话直接看代码

    首先引入ajaxfileupload.js 网上也有很多下面的代码是我自己测试过的

      1 jQuery.extend({  
      2     createUploadIframe: function (id, uri) {//id为当前系统时间字符串,uri是外部传入的json对象的一个参数  
      3         //create frame  
      4         var frameId = 'jUploadFrame' + id; //给iframe添加一个独一无二的id  
      5         var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //创建iframe元素  
      6         if (window.ActiveXObject) {//判断浏览器是否支持ActiveX控件  
      7             if (typeof uri == 'boolean') {  
      8                 iframeHtml += ' src="' + 'javascript:false' + '"';  
      9             }            else if (typeof uri == 'string') {  
     10                 iframeHtml += ' src="' + uri + '"';  
     11             }  
     12         }  
     13         iframeHtml += ' />';  
     14         jQuery(iframeHtml).appendTo(document.body); //将动态iframe追加到body中  
     15         return jQuery('#' + frameId).get(0); //返回iframe对象  
     16     },  
     17     createUploadForm: function (id, fileElementId, data) {//id为当前系统时间字符串,fileElementId为页面<input type='file' />的id,data的值需要根据传入json的键来决定  
     18         //create form      
     19         var formId = 'jUploadForm' + id; //给form添加一个独一无二的id  
     20         var fileId = 'jUploadFile' + id; //给<input type='file' />添加一个独一无二的id  
     21         var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //创建form元素  
     22         if (data) {//通常为false  
     23             for (var i in data) {  
     24                 if (data[i] instanceof Array) {
     25                     for ( var j in data[i]) {
     26                         jQuery('<input type="checkbox" name="'+i+'" value="'+data[i][j]+'" checked />').appendTo(form);
     27                     }
     28                 } else {
     29                     jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根据data的内容,创建隐藏域,这部分我还不知道是什么时候用到。估计是传入json的时候,如果默认传一些参数的话要用到。  
     30                 }
     31             }  
     32         }
     33         if (fileElementId instanceof Array) {
     34             for (var i = 0; i < fileElementId.length; i++) {
     35                 var oldElement = jQuery('#' + fileElementId[i]); //得到页面中的<input type='file' />对象  
     36                 var newElement = jQuery(oldElement).clone(); //克隆页面中的<input type='file' />对象  
     37                 jQuery(oldElement).attr('id', fileElementId[i]); //修改原对象的id  
     38                 jQuery(oldElement).before(newElement); //在原对象前插入克隆对象  
     39                 jQuery(oldElement).appendTo(form); //把原
     40             }
     41         } else {
     42             var oldElement = jQuery('#' + fileElementId); //得到页面中的<input type='file' />对象  
     43             var newElement = jQuery(oldElement).clone(); //克隆页面中的<input type='file' />对象  
     44             jQuery(oldElement).attr('id', fileId); //修改原对象的id  
     45             jQuery(oldElement).before(newElement); //在原对象前插入克隆对象  
     46             jQuery(oldElement).appendTo(form); //把原对象插入到动态form的结尾处  
     47         }
     48 
     49         //set attributes  
     50         jQuery(form).css('position', 'absolute'); //给动态form添加样式,使其浮动起来,  
     51         jQuery(form).css('top', '-1200px');  
     52         jQuery(form).css('left', '-1200px');  
     53         jQuery(form).appendTo('body'); //把动态form插入到body中  
     54         return form;  
     55     },  
     56     ajaxFileUpload: function (s) {//这里s是个json对象,传入一些ajax的参数  
     57         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout          
     58         s = jQuery.extend({}, jQuery.ajaxSettings, s); //此时的s对象是由jQuery.ajaxSettings和原s对象扩展后的对象  
     59         var id = new Date().getTime(); //取当前系统时间,目的是得到一个独一无二的数字  
     60         var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //创建动态form  
     61         var io = jQuery.createUploadIframe(id, s.secureuri); //创建动态iframe  
     62         var frameId = 'jUploadFrame' + id; //动态iframe的id  
     63         var formId = 'jUploadForm' + id; //动态form的id  
     64         // Watch for a new set of requests  
     65         if (s.global && !jQuery.active++) {//当jQuery开始一个ajax请求时发生  
     66             jQuery.event.trigger("ajaxStart"); //触发ajaxStart方法  
     67         }        var requestDone = false; //请求完成标志  
     68         // Create the request object  
     69         var xml = {};        if (s.global)  
     70             jQuery.event.trigger("ajaxSend", [xml, s]); //触发ajaxSend方法  
     71         // Wait for a response to come back  
     72         var uploadCallback = function (isTimeout) {//回调函数  
     73             var io = document.getElementById(frameId); //得到iframe对象  
     74             try {                if (io.contentWindow) {//动态iframe所在窗口对象是否存在  
     75                     xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;  
     76                     xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;  
     77                 } else if (io.contentDocument) {//动态iframe的文档对象是否存在  
     78                     xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;  
     79                     xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;  
     80                 }  
     81             } catch (e) {  
     82                 jQuery.handleError(s, xml, null, e);  
     83             }            if (xml || isTimeout == "timeout") {//xml变量被赋值或者isTimeout == "timeout"都表示请求发出,并且有响应  
     84                 requestDone = true; //请求完成  
     85                 var status;                try {  
     86                     status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超时”,表示请求成功  
     87                     // Make sure that the request was successful or notmodified  
     88                     if (status != "error") {                        // process the data (runs the xml through httpData regardless of callback)  
     89                         var data = jQuery.uploadHttpData(xml, s.dataType); //根据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果  
     90                         // If a local callback was specified, fire it and pass it the data  
     91                         if (s.success)  
     92                             s.success(data, status); //执行上传成功的操作  
     93                         // Fire the global callback  
     94                         if (s.global)  
     95                             jQuery.event.trigger("ajaxSuccess", [xml, s]);  
     96                     } else  
     97                         jQuery.handleError(s, xml, status);  
     98                 } catch (e) {  
     99                     status = "error";  
    100                     jQuery.handleError(s, xml, status, e);  
    101                 }                // The request was completed  
    102                 if (s.global)  
    103                     jQuery.event.trigger("ajaxComplete", [xml, s]);                // Handle the global AJAX counter  
    104                 if (s.global && ! --jQuery.active)  
    105                     jQuery.event.trigger("ajaxStop");                // Process result  
    106                 if (s.complete)  
    107                     s.complete(xml, status);  
    108                 jQuery(io).unbind();//移除iframe的事件处理程序  
    109                 setTimeout(function () {//设置超时时间  
    110                     try {  
    111                         jQuery(io).remove();//移除动态iframe  
    112                         jQuery(form).remove();//移除动态form  
    113                     } catch (e) {  
    114                         jQuery.handleError(s, xml, null, e);  
    115                     }  
    116                 }, 100)  
    117                 xml = null  
    118             }  
    119         }        // Timeout checker  
    120         if (s.timeout > 0) {//超时检测  
    121             setTimeout(function () {                // Check to see if the request is still happening  
    122                 if (!requestDone) uploadCallback("timeout");//如果请求仍未完成,就发送超时信号  
    123             }, s.timeout);  
    124         }        try {            var form = jQuery('#' + formId);  
    125             jQuery(form).attr('action', s.url);//传入的ajax页面导向url  
    126             jQuery(form).attr('method', 'POST');//设置提交表单方式  
    127             jQuery(form).attr('target', frameId);//返回的目标iframe,就是创建的动态iframe  
    128             if (form.encoding) {//选择编码方式  
    129                 jQuery(form).attr('encoding', 'multipart/form-data');  
    130             }            else {  
    131                 jQuery(form).attr('enctype', 'multipart/form-data');  
    132             }  
    133             jQuery(form).submit();//提交form表单  
    134         } catch (e) {  
    135             jQuery.handleError(s, xml, null, e);  
    136         }  
    137         jQuery('#' + frameId).load(uploadCallback); //ajax 请求从服务器加载数据,同时传入回调函数  
    138         return { abort: function () { } };  
    139     },  
    140     uploadHttpData: function (r, type) {        var data = !type;  
    141         data = type == "xml" || data ? r.responseXML : r.responseText;        // If the type is "script", eval it in global context  
    142         if (type == "script")  
    143             jQuery.globalEval(data);        // Get the JavaScript object, if JSON is used.  
    144         if (type == "json")  
    145             data=data.replace("<pre>","").replace("</pre>","");//除去字符串中的pre标签
    146             data=eval('(' + data+ ')');        // evaluate scripts within html  
    147             return data;
    148         if (type == "html")  
    149             jQuery("<div>").html(data).evalScripts();        return data;  
    150     },
    151     //自添加方法handleError
    152     handleError: function( s, xhr, status, e )      {
    153         // If a local callback was specified, fire it
    154         if ( s.error ) {
    155             s.error.call( s.context || s, xhr, status, e );
    156         }
    157         // Fire the global callback
    158         if ( s.global ) {
    159             (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
    160         }
    161     }
    162 }) 

    接下来就是上传文件操作了 ,我上传的是图片可以多图上传哦

    function uploadAgree(obj){
             var f=$(obj).val();
             if(f == null || f ==undefined || f == ''){
                 return false;
             }else if(!/.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f)){
                 alert("类型必须是图片(.png|jpg|bmp|gif|PNG|JPG|BMP|GIF)");
                 $(obj).val('');
                 return false;
             }else{
                //批量上传图片
                 $.ajaxFileUpload({
                      url:"/uploadPictureList",//需要链接到服务器地址   
                       secureuri:false,  
                       fileElementId:"uploadagree",//文件选择框的id属性  ,//文件选择框的id属性  
                       dataType: 'json',   //json 
                       contentType: false,    //不可缺
                      processData: false,    //不可缺
                     success: function (data){
                         if(data!=null){
                             $.each(data,function(i,url){
                                //拼接图片列表 
                                  var id = $('#detailImgs li:last').attr('id');
                                      id = id.substr(1);
                                      id = parseInt(id) + 1;
                                      var ids=id;
                                      id = 'P'+id;                                                    
                                  var a_hidden="<li style='100px;height:100px;margin-right:5px;' id='"+ id +"'><input type='hidden' value='"+url+"' name='imgs'>";
                                  var img_html="<img style='100%;height:100%'  src='"+url+"'  onclick='showOriginal(this)' original='"+url+"'>";
                                  var a_html="<a class='del_img_a' href='javascript:void(0);' onclick='delespan1("+ids+")'>删除</a>";
                                  var li_html="</li>";
                                  var length_=$('#detailImgs').find("li").length;
                                  if(length_<6){
                                      $('#detailImgs').append(a_hidden+img_html+a_html+li_html);
                                  }else{
                                      alert("最多添加5张图片");
                                      return false;
                                  }
                             });
                             
                         }else{
                             alert("上传失败");
                             $("#url").val("");
                             $(obj).val('');
                         }                   
                     },
                     error:function(XMLHttpRequest, textStatus, errorThrown){  
                         alert("上传失败,请检查网络后重试");
                         $("#url").val("");
                         $(obj).val('');
                    } 
                 });
             }
        }
        //上传之后删除
        function delespan1(id){
               $('#P'+id).remove();
        }

    HTML 代码:

     <div style="height:200px;margin:20px;;">
         <input type="hidden" id="employ_id"/>
         <input type="file" name="file" id="uploadagree" multiple="multiple" onchange="uploadAgree(this)"/>
         <ul id="detailImgs" style="overflow: hidden;margin-top:20px;">
             <li style="display:none;" id="P0">                                       
         </ul>
     </div>

    后台接收controller层代码:

     1 @RequestMapping("/uploadPictureList")
     2     @ResponseBody
     3     public String uploadPictureList(@RequestParam(value="file",required=false)MultipartFile[] file,HttpServletRequest request) {
     4         
     5          File targetFile=null;
     6             String msg="";//返回存储路径
     7             int code=1;
     8             List imgList=new ArrayList();
     9             if (file!=null && file.length>0) {
    10                 for (int i = 0; i < file.length; i++) {
    11                     String fileName=file[i].getOriginalFilename();//获取文件名加后缀
    12                    // String paths="/upload/hr/employee/";
    13                     if(fileName!=null&&fileName!=""){   
    14                         String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/hr/employee/";//存储路径
    15                         String path = request.getSession().getServletContext().getRealPath("/upload/hr/employee/"); //文件存储位置
    16                         String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
    17                         fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名
    18 
    19                         //先判断文件是否存在
    20                         File file1 =new File(path); 
    21                         //如果文件夹不存在则创建    
    22                         if(!file1 .exists()  && !file1 .isDirectory()){       
    23                             file1 .mkdir();  
    24                         }
    25                         targetFile = new File(file1, fileName);
    26                         try {
    27                             file[i].transferTo(targetFile);
    28                            // msg=returnUrl+fileName;
    29                             msg="/upload/hr/employee/"+fileName;
    30                             imgList.add(msg);
    31                         } catch (Exception e) {
    32                             e.printStackTrace();
    33                         }
    34                     }
    35                 }
    36             }               
    37      return JSON.toJSONString(imgList);
    38     }

    到这里就基本完成了!!!

    --------------------------------请多多指教

  • 相关阅读:
    产生渐变色的view
    新建一个去除storyboard的项目
    绘制波形图
    文件系统扫描的工具类
    如何动态绘制时钟
    Xcode插件管理器Alcatraz的使用
    UITableView的headerView展开缩放动画
    POPSpring动画参数详解
    Java枚举类使用和总结
    Java判断不为空的工具类总结
  • 原文地址:https://www.cnblogs.com/livedian/p/10598143.html
Copyright © 2011-2022 走看看