SWFupload+servlet 实现多图片上传

目标 
1.使用 swfuplaod3.5+servlet 实现多图片上传 

效果图: 
注: 
1.  里面有遮罩层 
2.  谈出的层可以拖动 
3.  加入了进度条 
4.  里面采用jquery 注意引用js 
5.  google. firefox ie 测试通过 
6.  在"允许用户同时上传 20 张图片,单张图片容量不超过1 MB" 上面有个 错误信息层(用于显示上传结果,加载swfupload失败 等详情分析handlers.js) 
7.  处理 swfupload 兼容 ie9 上传按钮不出来 问题 ; 
8.  红色框:功能主要是在KindEditor中使用(handlers.js 中给注释了) 

 

目录: 
 

需要的jar 
commons-fileupload-1.2.jar 
commons-io-1.3.2.jar 

index.jsp 
Html代码   收藏代码
  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. <%@ page isELIgnored="false" %>   
  3. <%  
  4.     String path = request.getContextPath();  
  5.     String basePath = request.getScheme() + "://"  
  6.             + request.getServerName() + ":" + request.getServerPort()  
  7.             + path + "/";  
  8. %>  
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  10. <html>  
  11. <head>  
  12. <base href="<%=basePath%>">  
  13. <title>文件上传工具V2.1</title>  
  14.   
  15. <link href="${pageContext.request.contextPath}/css/default.css" rel="stylesheet"type="text/css" />  
  16. <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-latest.js"></script>  
  17. <script type="text/javascript" src="${pageContext.request.contextPath}/js/swfupload.js"></script>  
  18. <script type="text/javascript" src="${pageContext.request.contextPath}/js/handlers.js"></script>  
  19.   
  20. <script type="text/javascript">  
  21.     var contextPath="${pageContext.request.contextPath}";  
  22.     function startLoad(){  
  23.         var url=contextPath+"/servlet/FileUploadServlet.htm?jsessionId=${pageContext.session.id}"; //处理上传的servlet  
  24.         var sizeLimit="1 MB";// 文件的大小  注意: 中间要有空格  
  25.         var types="*.jpg;*.jpeg;*.gif"; //注意是 " ; " 分割   
  26.         var typesdesc="web iamge file"; //这里可以自定义  
  27.         var uploadLimit=20;  //上传文件的 个数  
  28.         initSwfupload(url,sizeLimit,types,typesdesc,uploadLimit);  
  29.     }  
  30. </script>  
  31. </head>  
  32. <body>  
  33. <center>  
  34. <input type="button" onclick="startLoad()" value="批量图片上传"/></center>  
  35. </body>  
  36. </html>  

handlers.js 
Java代码   收藏代码
  1. var swfu;  
  2. var insertAllStatus=true//全部插入按钮的状态  
  3. //初始化 swf  
  4. function initSwfupload(url,sizeLimit,types,typsdesc,uploadLimit){  
  5.         //初始化界面  
  6.         init(uploadLimit,sizeLimit);  
  7.         //初始化 swfupload  
  8.         var settings={  
  9.             // Flash Settings flash9_url :"http://192.168.1.115:8080/bjsearch/js/plugins/multiimage/js/swfupload_fp9.swf",  
  10.             flash_url : contextPath+"/js/swfupload.swf",  
  11.             file_post_name:"filedata",  
  12.               
  13.             upload_url: url,// contextPath+"/servlet/FileUploadServlet.htm?jsessionId=${pageContext.session.id}",  
  14.             post_params: {"name" : "test"},  
  15.               
  16.             // File Upload Settings  
  17.             file_size_limit : sizeLimit,    // 1000MB  
  18.             file_types : types,    //*.*  
  19.             file_types_description : typsdesc,//"Web Image Files",  
  20.             file_upload_limit : uploadLimit,//20  
  21.             file_queue_limit : 0,  
  22.               
  23.             file_queue_error_handler : fileQueueError,  
  24.             file_dialog_complete_handler : fileDialogComplete,//选择好文件后提交  
  25.             file_queued_handler : fileQueued,  
  26.             swfupload_load_failed_handler : swfUploadLoadFailed, //swf 加载失败  
  27.             swfupload_loaded_handler : swfUploadLoaded,  //swf 加载完成  
  28.               
  29.             upload_start_handler: uploadStart,  
  30.             upload_progress_handler : uploadProgress,  
  31.             upload_error_handler : uploadError,  
  32.             upload_success_handler : uploadSuccess,  
  33.             upload_complete_handler : uploadComplete,  
  34.   
  35.             // Button Settings  
  36.             button_image_url : contextPath+"/images/select-files-zh_CN.png",  
  37.             button_placeholder_id : "buttonPlaceholder",  
  38.             button_width: 72,  
  39.             button_height: 23,  
  40.             button_text : '<span style="display:block;"></span>',  
  41.             custom_settings : {  
  42.                 photoContainer_Id   : "photoContainer",     //图片的容器id  
  43.                 btnUpload_ID        : "btnUpload",          //上传按钮  
  44.                 insertAll_Id        : "insertAll",          //全部插入  
  45.                 clearAll_Id         : "clearAll",           //全部清空  
  46.                 errorMsg_Id         : "errorMsg",           //错误信息  
  47.                 errorMsg_fadeOutTime: 2000                  //错误信息谈出的时间  
  48.             },  
  49.             // Debug Settings  
  50.             debug: false,   //是否显示调试窗口  
  51.             auto_upload:false  
  52.         };  
  53.     try{  
  54.         //等 1秒后初始化 swf  
  55.         setTimeout(function (){swfu = new SWFUpload(settings);},1000);  
  56.     }catch (ex) {  
  57.         var message='<div id="divAlternateContent" style="background-color: #FFFF66; text-align:center;">'  
  58.             +'<font color="red">工具加载失败,请刷新再试!</div>';  
  59.         addErrorMsg(message,false);  
  60.         this.debug(ex);  
  61.     }  
  62.       
  63. }  
  64. //初始化 界面  
  65. function init(uploadLimit,sizeLimit){  
  66.     if($(".ke-dialog-upload").length>0){  
  67.         $(".ke-dialog-upload").remove();  
  68.     }  
  69.     var uploadbody='<div id="uploadBody" class="ke-dialog-upload">'  
  70.         +'<div id="uploadHead" class="ke-dialog-upload-head">'  
  71.         +'  <div style="float: left">批量图片上传</div><div id="iconClose" class="ke-dialog-icon-close" title="关闭"></div><div style="clear: both"></div>'  
  72.         +'  </div>'  
  73.         +'  <!--content-->'  
  74.         +'  <div class="ke-dialog-content">'  
  75.         +'      <div class="ke-dialog-content-head">'  
  76.         +'        <div id="errorMsg" class="ke-dialog-content-error"></div>'  
  77.         +'        <div id="swfbuttonParent" class="ke-swfupload-button"><span id="buttonPlaceholder" /></div>'  
  78.         +'        <div class="ke-inline-block ke-swfupload-desc">允许用户同时上传 <font color="red">'+uploadLimit+'</font> 张图片,单张图片容量不超过<font color="red">'+sizeLimit+'</font></div>'  
  79.         +'          <div class="ke-button-common ke-button-outer ke-swfupload-startupload"><input id="btnUpload" type="button" class="ke-button-common ke-button" value="开始上传"></div>'  
  80.         +'          <div style="clear: both;"></div>'         
  81.         +'      </div>'  
  82.         +'      <div id="photoContainer" class="ke-swfupload-body">'  
  83.         +'      </div>'  
  84.         +'  </div>'  
  85.         +'  <!--bottom-->'  
  86.         +'  <div class="ke-dialog-footer">'  
  87.         +'  <span class="ke-button-common ke-button-outer" title="全部插入"><input id="insertAll" class="ke-button-common ke-button" type="button" value="全部插入"></span>'  
  88.         +'  <span class="ke-button-common ke-button-outer" title="全部清空"><input id="clearAll" class="ke-button-common ke-button" type="button" value="全部清空"></span>'  
  89.         +'  <span class="ke-button-common ke-button-outer" title="取消"><input id="btncancel" class="ke-button-common ke-button" type="button" value="取消"></span></div>'  
  90.         +'  </div> '  
  91.         +'<div style="display: block; width: 1903px; height: 12702px; position: absolute; left: 0px; top: 0px; z-index: 811212;" class="ke-dialog-mask"></div>';  
  92.     $('body').append(uploadbody);  
  93.     $("#iconClose").bind("click",{uploadBodyId:'uploadBody'},iconClose);  
  94.     $("#btncancel").bind("click",{uploadBodyId:'uploadBody'},iconClose);  
  95.    
  96. //处理 鼠标拖动层  
  97.     var dragging = false;  
  98.     var iX, iY;  
  99.     $("#uploadHead").mousedown(function(e) {  
  100.         dragging = true;  
  101.         iX = e.clientX - this.offsetParent.offsetLeft;  
  102.         iY = e.clientY - this.offsetParent.offsetTop;  
  103.         return false;  
  104.     });  
  105.     document.onmousemove = function(e) {  
  106.         if (dragging) {  
  107.             var e = e || window.event;  
  108.             var oX = e.clientX - iX;  
  109.             var oY = e.clientY - iY;  
  110.             $("#uploadBody").css({"left":oX<0?0:oX + "px""top":oY<0?0:oY + "px"});  
  111.             return false;  
  112.         }  
  113.     };  
  114.     $(document).mouseup(function(e) {  
  115.         dragging = false;  
  116.         e.cancelBubble = true;  
  117.     });  
  118. }  
  119. /**  
  120.  * 当文件选择对话框关闭消失时,如果选择的文件成功加入上传队列,  
  121.  * 那么针对每个成功加入的文件都会触发一次该事件(N个文件成功加入队列,就触发N次此事件)。  
  122.  * @param {} file  
  123.  * id : string,             // SWFUpload控制的文件的id,通过指定该id可启动此文件的上传、退出上传等  
  124.  * index : number,          // 文件在选定文件队列(包括出错、退出、排队的文件)中的索引,getFile可使用此索引  
  125.  * name : string,           // 文件名,不包括文件的路径。  
  126.  * size : number,           // 文件字节数  
  127.  * type : string,           // 客户端操作系统设置的文件类型  
  128.  * creationdate : Date,     // 文件的创建时间  
  129.  * modificationdate : Date, // 文件的最后修改时间  
  130.  * filestatus : number      // 文件的当前状态,对应的状态代码可查看SWFUpload.FILE_STATUS   
  131.  */  
  132.    
  133. // 关闭 /取消 按钮 事件  
  134. function iconClose(event){  
  135.     if(typeof swfu != 'undefined' || swfu!=null){  
  136.         swfu.destroy();  
  137.     }  
  138.     $("#"+event.data.uploadBodyId).remove();  
  139.     $(".ke-dialog-mask").remove();  
  140.     insertAllStatus=true;  
  141. }  
  142.   
  143. //全部清空  
  144. function clearUpload(){  
  145.     $("div[id^='SWFUpload_']").each(function(i,obj){  
  146.         deleteFile($(obj).attr('id'));  
  147.     });  
  148. }  
  149. // 全部插入  
  150. function insertAllevent(){  
  151.     //alert(swfu.getStats().successful_uploads);//successful_uploads  
  152.     $("img[data-status='0']").each(function(i,obj){  
  153.             var showimg = new Image();  
  154.             showimg.src=$(obj).attr("src");  
  155.             var width = showimg.width;  
  156.             var height = showimg.height;  
  157.             var title=$(obj).attr("title");  
  158.             var url=$(obj).attr("src");  
  159.             //KE.plugin['multiimage'].insert("ArticleBody",url, title,width,height,"0","");  
  160.     });  
  161.     $("#iconClose").trigger("click");  
  162. }  
  163.   
  164. // 添加错误信息  
  165. function addErrorMsg(message,isFadeOut){  
  166.     $("#"+swfu.customSettings.errorMsg_Id).empty().html(message);  
  167.     if(isFadeOut){  
  168.         setTimeout(function () {  
  169.             $("#"+swfu.customSettings.errorMsg_Id).children().fadeOut(1000);  
  170.         },parseInt(swfu.customSettings.errorMsg_fadeOutTime));  
  171.     }  
  172. }  
  173.   
  174. //鼠标 移入 移出的 背景效果  
  175. function photoMouseOver(){  
  176.     $(this).addClass("ke-on");  
  177. }  
  178. function photoMouseOut(obj){  
  179.     $(this).removeClass("ke-on");  
  180. }  
  181.   
  182. //swf 准备加载  为使用  
  183. function swfUploadPreLoad() {  
  184.     var self = this;  
  185.     var loading = function () {  
  186.         var longLoad = function () {  
  187.             document.getElementById("divLoadingContent").style.display = "none";  
  188.             document.getElementById("divLongLoading").style.display = "";  
  189.         };  
  190.         this.customSettings.loadingTimeout = setTimeout(function () {  
  191.                 longLoad.call(self)  
  192.             },  
  193.             15 * 1000  
  194.         );  
  195.     };  
  196.       
  197.     this.customSettings.loadingTimeout = setTimeout(function () {  
  198.             loading.call(self);  
  199.         },  
  200.         1*1000  
  201.     );  
  202. }  
  203.   
  204. //swf 加载失败  
  205. function swfUploadLoadFailed() {  
  206.     //clearTimeout(this.customSettings.loadingTimeout);  
  207.     var message='<div id="divAlternateContent" style="background-color: #FFFF66; text-align:center;">'  
  208.             +'[url=http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash]<font color="red">请安装或者升级您的Flash插件!</font>[/url]</div>';  
  209.     addErrorMsg(message,false);  
  210. }  
  211.   
  212. //swf 加载 完成  
  213. function swfUploadLoaded() {  
  214.     //var self = this;  
  215.     //clearTimeout(this.customSettings.loadingTimeout);  
  216.     addErrorMsg("",false);  
  217.     $("#"+this.customSettings.btnUpload_ID).click(function (){swfu.startUpload()});  
  218. }  
  219.   
  220.   
  221.  //每次被加入 到列队中  
  222. function fileQueued(file){  
  223.     addReadyFileInfo(file.id,file.name,"等待上传");  
  224. }  
  225.   
  226. //文件对话框选择完成  
  227. function fileDialogComplete(numFilesSelected, numFilesQueued) {  
  228.     try {  
  229.         if (numFilesQueued > 0) {  
  230.             $("#"+this.customSettings.clearAll_Id).bind("click",clearUpload);  
  231.         }  
  232.         if(this.settings.auto_upload){//是否要上传  
  233.             this.startUpload();  
  234.         }  
  235.     } catch (ex) {  
  236.         this.debug(ex);  
  237.     }  
  238. }  
  239. //都加入列队中 的错误信息  
  240. function fileQueueError(file, errorCode, message) {  
  241.     try {  
  242.         switch (errorCode) {  
  243.         case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:  
  244.             message = "<font color='red'>数量超过"+swfu.getSetting('file_upload_limit')+"张啦!</font>";  
  245.             break;  
  246.         case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:  
  247.             message =  "<font color='red'>文件超过"+swfu.getSetting('file_size_limit')+"啦!</font>";  
  248.             break;  
  249.         case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:  
  250.             message = "<font color='red'>文件不能为空哦!";  
  251.         case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:  
  252.             message = "<font color='red'>文件格式只能为"+swfu.getSetting('fileTypes')+"!</font>";  
  253.             break;  
  254.         default:  
  255.             message="<font color='red'>选择文件发生错误!"+"</font>";  
  256.             return;  
  257.         }  
  258.         addErrorMsg(message,true);  
  259.         //addReadyFileInfo(file.id,file.name,"上传错误")+"</font>";  
  260.     } catch (ex) {  
  261.         this.debug(ex);  
  262.     }  
  263. }  
  264.   
  265.   
  266. // 开始上传   
  267. function uploadStart(file){  
  268.     $("#"+file.id).find(".ke-progressbar").css("display","block");  
  269.     $("#"+file.id).find(".ke-message").css("display","none");         
  270. }  
  271. // 上传的进度  
  272. function uploadProgress(file, bytesLoaded) {  
  273.     try {  
  274.         var percent = Math.ceil((bytesLoaded / file.size) * 100);  
  275.           
  276.         if(percent>100){  
  277.             percent=100;  
  278.         }  
  279.         var progress = new FileProgress(file);  
  280.         progress.setProgress(percent);  
  281.         if (percent === 100) {  
  282.             //progress.setStatus("建缩略图...");//正在创建缩略图...  
  283.             //progress.toggleCancel(false, this);  
  284.         }else {  
  285.             progress.setStatus("正在上传...");  
  286.             progress.toggleCancel(truethis);  
  287.         }  
  288.     }catch (ex) {  
  289.         this.debug(ex);  
  290.     }  
  291. }  
  292.   
  293. // 上传到服务器后 的放回信息  
  294. function uploadSuccess(file, serverData) {  
  295.     try {  
  296.         var progress = new FileProgress(file);  
  297.           
  298.         var data = eval("(" + serverData + ")");  
  299.         $("#"+file.id).find(".ke-img").attr("data-status",data.status);  
  300.         if (data.status == 0 || data.status == "0") {  
  301.             $("#"+file.id).find(".ke-img").attr("src",contextPath+data.message);  
  302.             progress.setStatus("上传成功");  
  303.             progress.toggleCancel();  
  304.             if(insertAllStatus){  
  305.                 if(swfu.getStats().successful_uploads>0){  
  306.                     $("#"+swfu.customSettings.insertAll_Id).bind("click",insertAllevent);  
  307.                 }  
  308.                 insertAllStatus=false;  
  309.             }  
  310.             return;  
  311.         }else if(data.status == 1 || data.status == "1"){  
  312.             progress.setStatus("上传失败");  
  313.         }else if(data.status == 2 || data.status == "2"){  
  314.             progress.setStatus("格式不对");  
  315.         }else if(data.status == 3 || data.status == "3"){  
  316.             progress.setStatus("文件超大");  
  317.         }else if(data.status == 4 || data.status == "4"){  
  318.             progress.setStatus("文件为空");  
  319.         }else if(data.status == 5 || data.status == "6"){  
  320.             progress.setStatus("路径不对");  
  321.         }else{  
  322.             progress.setStatus("上传失败");  
  323.         }  
  324.         progress.toggleCancel(false);  
  325.     } catch (ex) {  
  326.         this.debug(ex);  
  327.     }  
  328. }  
  329.   
  330. // 选择文件后 添加到 操作层中  
  331. function addReadyFileInfo(fileid,fileName,message){  
  332.     var photoDiv='<div class="ke-inline-block ke-item" id="'+fileid+'">'  
  333.             +'<div class="ke-inline-block ke-photo" style="height:80px; width:80px;">'  
  334.             +'  [img]'+contextPath+'/images/image.png" class="ke-img" data-status="-1" width="80" height="80[/img]'  
  335.             +'      <span class="ke-delete"></span>'  
  336.             +'          <div class="ke-status">'  
  337.             +'              <div class="ke-progressbar" style="display: none;">'  
  338.             +'                   <div class="ke-progressbar-bar">'  
  339.             +'                      <div class="ke-progressbar-bar-inner"></div>'  
  340.             +'                   </div>'  
  341.             +'                  <div class="ke-progressbar-percent">0%</div>'  
  342.             +'               </div>'  
  343.             +'              <div class="ke-message">'+message+'</div>'  
  344.             +'          </div>'  
  345.             +'      </div>'  
  346.             +'  <div class="ke-name" alt="'+fileName+'">'+fileName+'</div>'  
  347.             +'</div>';  
  348.               
  349.     $("#"+swfu.customSettings.photoContainer_Id).append(photoDiv);  
  350.     $("#"+fileid).find(".ke-photo").bind("mouseover",photoMouseOver).bind("mouseout",photoMouseOut);  
  351.     $("#"+fileid).find(".ke-delete").bind("click",function(){deleteFile(fileid)});  
  352. }  
  353.   
  354.   
  355. // 删除 单个文件   
  356. function deleteFile(fileId){  
  357.     $("#"+fileId).remove();  
  358.     swfu.cancelUpload(fileId,false);  
  359. }  
  360.   
  361. // 单个 文件上传完    
  362. function uploadComplete(file) {   
  363.     try {  
  364.         /*  I want the next upload to continue automatically so I'll call startUpload here */  
  365.         if (this.getStats().files_queued > 0) {  
  366.             this.startUpload();  
  367.         }  
  368.     } catch (ex) {  
  369.         this.debug(ex);  
  370.     }  
  371. }  
  372. //上传的错误  
  373. function uploadError(file, errorCode, message) {  
  374.     var message =  "<font color='red'>文件上传出错!</font>";  
  375.     var progress = new FileProgress(file);  
  376.     var flag=false;  
  377.     try {  
  378.         switch (errorCode) {  
  379.         case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:  
  380.                 progress.setStatus("取消上传");  
  381.                 progress.toggleCancel(false);  
  382.                 break;  
  383.         case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:  
  384.                 progress.setStatus("停止上传");  
  385.                 progress.toggleCancel(true);  
  386.         case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:  
  387.                 progress.setStatus("文件超大");  
  388.                 progress.toggleCancel(false);  
  389.                 break;  
  390.         default:  
  391.             addErrorMsg(message,true);  
  392.             break;  
  393.         }  
  394.         //addFileInfo(file.id,imageName);  
  395.     } catch (ex3) {  
  396.         this.debug(ex3);  
  397.     }  
  398.   
  399. }  
  400.   
  401. // 根据 src 添加 图片  
  402. function addImage(src) {  
  403.     var newImg = document.createElement("img");  
  404.     newImg.style.margin = "5px";  
  405.   
  406.     //document.getElementById("thumbnails").appendChild(newImg);  
  407.     if (newImg.filters) {  
  408.         try {  
  409.             newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;  
  410.         } catch (e) {  
  411.             // If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.  
  412.             newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';  
  413.         }  
  414.     } else {  
  415.         newImg.style.opacity = 0;  
  416.     }  
  417.   
  418.     newImg.onload = function () {  
  419.         fadeIn(newImg, 0);  
  420.     };  
  421.     newImg.src = src;  
  422. }  
  423.   
  424. function fadeIn(element, opacity) {  
  425.     var reduceOpacityBy = 5;  
  426.     var rate = 30;  // 15 fps  
  427.   
  428.   
  429.     if (opacity < 100) {  
  430.         opacity += reduceOpacityBy;  
  431.         if (opacity > 100) {  
  432.             opacity = 100;  
  433.         }  
  434.   
  435.         if (element.filters) {  
  436.             try {  
  437.                 element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;  
  438.             } catch (e) {  
  439.                 // If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.  
  440.                 element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';  
  441.             }  
  442.         } else {  
  443.             element.style.opacity = opacity / 100;  
  444.         }  
  445.     }  
  446.   
  447.     if (opacity < 100) {  
  448.         setTimeout(function () {  
  449.             fadeIn(element, opacity);  
  450.         }, rate);  
  451.     }  
  452. }  
  453.   
  454. /* ****************************************** 
  455.  *  This event comes from the Queue Plugin 
  456.  * ****************************************** */  
  457. function queueComplete(numFilesUploaded) {  
  458.      //this.getStats().successful_uploads;  
  459. }  
  460.   
  461. /* ****************************************** 
  462.  *  FileProgress Object 
  463.  *  Control object for displaying file info 
  464.  * ****************************************** */  
  465.   
  466. function FileProgress(file) {  
  467.     var fileID = file.id;  
  468.     this.fileProgressWrapper = $("#"+file.id).find(".ke-status"); //document.getElementById(this.fileProgressID);  
  469.     if (!this.fileProgressWrapper) {  
  470.         fadeIn(this.fileProgressWrapper, 0);  
  471.     }  
  472. }  
  473.   
  474. FileProgress.prototype.setProgress = function (percentage) {  
  475.     $(this.fileProgressWrapper).find(".ke-progressbar-bar-inner").css("width",percentage + "%");  
  476.     $(this.fileProgressWrapper).find(".ke-progressbar-percent").text(percentage + "%");  
  477. };  
  478.   
  479. FileProgress.prototype.setComplete = function () {  
  480.     $(this.fileProgressWrapper).find(".ke-progressbar-bar-inner").css("width","");  
  481. };  
  482.   
  483. FileProgress.prototype.setCancelled = function () {  
  484.     $(this.fileProgressWrapper).find(".ke-progressbar-bar-inner").css("width","");  
  485. };  
  486.   
  487. FileProgress.prototype.setStatus = function (status) {  
  488.     $(this.fileProgressWrapper).find(".ke-message").text(status);  
  489. };  
  490.   
  491. FileProgress.prototype.toggleCancel = function (show) {  
  492.     if(typeof show =='undefined'){  
  493.         $(this.fileProgressWrapper).find(".ke-progressbar").css("display""none");  
  494.         $(this.fileProgressWrapper).find(".ke-message").css("display","none";)  
  495.     }else{  
  496.         $(this.fileProgressWrapper).find(".ke-progressbar").css("display", show ? "block" : "none");  
  497.         $(this.fileProgressWrapper).find(".ke-message").css("display", show ? "none" : "block");  
  498.     }  
  499. };  


//处理 ie 9 的兼容性 找到这个方法 修改下就可以了 
swfuplaod.js 
Java代码   收藏代码
  1. // Private: getFlashHTML generates the object tag needed to embed the flash in to the document  
  2. SWFUpload.prototype.getFlashHTML = function () {  
  3.     // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay  
  4.     var classid = '';  
  5.     if (KindEditor.IE && KindEditor.V > 8) {  
  6.         classid = ' classid = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';  
  7.     }  
  8.     return ['<object id="'this.movieName, '"' + classid + ' type="application/x-shockwave-flash" data="'this.settings.flash_url, '" width="'this.settings.button_width, '" height="'this.settings.button_height, '" class="swfupload">',  
  9.                 '<param name="wmode" value="'this.settings.button_window_mode, '" />',  
  10.                 '<param name="movie" value="'this.settings.flash_url, '" />',  
  11.                 '<param name="quality" value="high" />',  
  12.                 '<param name="menu" value="false" />',  
  13.                 '<param name="allowScriptAccess" value="always" />',  
  14.                 '<param name="flashvars" value="' + this.getFlashVars() + '" />',  
  15.                 '</object>'].join("");  
  16. };  


//简单的处理 文件上传 
FileUploadServlet.java 
Java代码   收藏代码
  1. package com.sh.common;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.PrintWriter;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Iterator;  
  8. import java.util.List;  
  9. import java.util.UUID;  
  10.   
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.http.HttpServlet;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. import javax.servlet.http.HttpServletResponse;  
  15.   
  16. import org.apache.commons.fileupload.FileItem;  
  17. import org.apache.commons.fileupload.FileItemFactory;  
  18. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  19. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  20.   
  21. import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;  
  22. import com.sun.org.apache.xml.internal.security.utils.Base64;  
  23.   
  24.   
  25. public class FileUploadServlet extends HttpServlet {  
  26.   
  27.     private static final int UPLOAD_SUCCSSS=0;    // "上传文件成功!",   
  28.     private static final int UPLOAD_FAILURE=1;    // "上传文件失败!"),   
  29.     private static final int UPLOAD_TYPE_ERROR=2// "上传文件类型错误!"),   
  30.     private static final int UPLOAD_OVERSIZE=3;   // "上传文件过大!"),  
  31.     private static final int UPLOAD_ZEROSIZE=4;   // "上传文件为空!"),  
  32.     private static final int UPLOAD_NOTFOUND=5;   // "上传文件路径错误!")  
  33.   
  34.       
  35.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  36.             throws ServletException, IOException {  
  37.   
  38.         doPost(request,response);  
  39.     }  
  40.   
  41.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  42.             throws ServletException, IOException {  
  43.           
  44.         response.setContentType("text/html; charset=UTF-8");  
  45.           
  46.         PrintWriter out=response.getWriter();  
  47.          String rootPath = request.getParameter("rootPath");    
  48.       
  49.          String param = request.getParameter("param");  
  50.            
  51.          if(rootPath == null) rootPath = "";    
  52.             rootPath = rootPath.trim();    
  53.          if(rootPath.equals("")){    
  54.              rootPath = this.getServletContext().getRealPath("");    
  55.          }    
  56.           
  57.          //上传操作    
  58.           FileItemFactory factory = new DiskFileItemFactory();    
  59.           ServletFileUpload upload = new ServletFileUpload(factory);    
  60.           upload.setHeaderEncoding("UTF-8");    
  61.           try{    
  62.               List items = upload.parseRequest(request);    
  63.               if(null != items){    
  64.                   Iterator itr = items.iterator();    
  65.                   while(itr.hasNext()){    
  66.                       FileItem item = (FileItem)itr.next();  
  67.                       if(item.isFormField()){    
  68.                          continue;    
  69.                       }else{    
  70.                            //以当前精确到秒的日期为上传的文件的文件名    
  71.                           SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddkkmmss");   
  72.                           String path="/files";  
  73.                           File savedFile = new File(rootPath+path,item.getName());    
  74.                           item.write(savedFile);   
  75.                             
  76.                           out.print("{status:"+this.UPLOAD_SUCCSSS+",message:'"+path+"/"+item.getName()+"'}");  
  77.                       }    
  78.                   }    
  79.               }    
  80.           }catch(Exception e){    
  81.               e.printStackTrace();    
  82.           }  
  83.               
  84.     }  
  85.   
  86.      /**  
  87.      * new文件名= 时间 + 全球唯一编号  
  88.      * @param fileName old文件名  
  89.      * @return new文件名  
  90.      */    
  91.     private String generateFileName(String fileName) {    
  92.         String uuid=UUID.randomUUID().toString();    
  93.         int position = fileName.lastIndexOf(".");       
  94.         String extension = fileName.substring(position);       
  95.         return uuid + extension;       
  96.     }    
  97. }  
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值