// jquery,artDialog,swfUpload //document.write("<script language=\"javascript\" src='..\/js\/j.js' > <\/script>"); var SRM_SWFUpload = SRM_SWFUpload || {}; SRM_SWFUpload.SPLITE = ':'; SRM_SWFUpload.ART_DIALOG_VER = art.dialog.fn.version; (function($){ $.fn.swfuInit= function(settings){ //默认参数 var defaultSettings = { // 附件ID,submit to server appendixId:'appendixId', // 附件源文件名, uploadFileName:'uploadFileName', // 附件重命名后 文件名 oldPath:'oldPath', // 上传文件时 的临时路径 picturePath:'picturePath', // 上传文件的大小 单位:字节 pictureSize:'pictureSize', // 附件ID,submit to server appendixIdVal:'', // 附件源文件名, uploadFileNameVal:'', // 附件重命名后 文件名 oldPathVal:'', // 上传文件时 的临时路径 picturePathVal:'', // 上传文件的大小 单位:字节 pictureSizeVal:'', // 上传按钮后的描述信息 descInfo:'点击此按钮可上传小于100M的附件', // 是否多选 multiple:false, // 提交文件域的参数名称 filePostName:'uploadFile', // 允许上传文件的类型,以 ; 分割,*.jpg;*.doc fileTyps:'*.*', fileTypesDesc : 'All File', fileSizeLimit : "100 MB", fileUploadLimit : 100, fileQueueLimit : 1, postParams : {}, down_file:function (url) { // 下载临时文件 window.open("../upload/download.action?fileUrl=" + url); }, showTip : true }; /* 合并默认参数和用户自定义参数 */ settings = $.extend(defaultSettings, settings); var _swfu ; this.each(function(){ // 方法体 var elem = $(this); if (!elem) { return ; } _swfu = new SRMSWFU(elem, settings); _swfu.generate(); }); return _swfu; }; /* * 私有函数 */ function SRMSWFU(elem, settings) { this.settings = settings; this.uploadDiv = elem; this.prefixName = elem.attr("id"); this.prefixIndex = SRM_SWFUpload.movieCount++; this.contextName = elem.attr("id"); this.progressTarget = elem.attr("id") + "fsUploadProgress"; this.cancelButtonId = elem.attr("id") + "btnCancel"; this.buttonId = elem.attr("id") + "spanButtonPlaceHolder"; this.divStatusId = elem.attr("id") + "divStatus"; this.biddingFileId = elem.attr("id") + "biddingFile"; this.delFileButtonId = elem.attr("id") + "delFileButton"; this.filePostName = settings.filePostName ? settings.filePostName : "uploadFile"; this.postParams = settings.postParams; this.SWF_SELECT_FILE_NAME = ""; this.swfuObject = {}; // 事件队列 this.eventQueue = []; }; SRMSWFU.prototype = { generate : function() { var self = this; // 初始化调用SWFUpload对象初始化 if (self.uploadDiv) { self.uploadDiv.html(""); } var htmls = self.generateHTML(self.uploadDiv); var upObjId = self.prefixName; var _swfSet = { file_types : self.settings.fileTyps, file_types_description : self.settings.fileTypesDesc, file_size_limit : self.settings.fileSizeLimit, // 最多上传文件数量 file_upload_limit : self.settings.fileUploadLimit, // 队列文件数量 file_queue_limit : self.settings.fileQueueLimit, debug: false, // Button settings // 单选OR多选 button_action : self.settings.multiple ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE, button_image_url: "../images/swf_btn_bg.gif", button_width: "76", button_height: "26", button_text: "<span class='theFont'>上传</span>", button_text_style: ".theFont { font-size: 11;font-weight:bold;text-align:center; color:#323d1f;background-color:transparent; }", button_text_left_padding: 1, button_text_top_padding: 4 , flash_url : "../js/SWFUpload/swfupload.swf", upload_url: "../upload/upload.action", // file_dialog_start_handler : fileDialogStart, file_post_name:self.filePostName, custom_settings : { progressTarget : self.progressTarget, cancelButtonId : self.cancelButtonId }, button_cursor: SWFUpload.CURSOR.HAND, post_params : self.postParams, button_placeholder_id:self.buttonId, file_dialog_complete_handler : function (numFilesSelected, numFilesQueued){ if (numFilesSelected > 0 && numFilesQueued > 0) { var dialog = art.dialog.confirm("确认要上传 "+self.SWF_SELECT_FILE_NAME+" 吗?",function(){ try { self.swfuObject.startUpload(); } catch (ex) { dialog.close(); } },function(){ // 取消了队列 self.swfuObject.cancelQueue(); }); } }, // 选中文件后确定后执行 file_queued_handler : function (file) { // 当文件选择对话框关闭消失时,如果选择的文件成功加入上传队列,那么针对每个成功加入的文件都会触发一次该事件(N个文件成功加入队列,就触发N次此事件)。 this.customSettings.queue = this.customSettings.queue || new Array(); // while (this.customSettings.queue.length > 0) { // this.cancelUpload(this.customSettings.queue.pop(), false); // } this.customSettings.queue.push(file.id); self.SWF_SELECT_FILE_NAME = self.SWF_SELECT_FILE_NAME + file.name + SRM_SWFUpload.SPLITE ; }, file_queue_error_handler : function (file, errorCode, message) { // this 已经是swfupload对象 try { if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) { // art.dialog.alert("文件队列已满,最多可上传 "+this.settings.file_upload_limit+" 个文件."); art.dialog.alert("一次最多能选择 "+this.settings.file_queue_limit+" 个文件."); return; } var progress = new FileProgress(file, this.customSettings.progressTarget); progress.setError(); progress.toggleCancel(false); switch (errorCode) { case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: progress.setStatus("File is too big."); art.dialog.alert("文件:" + file.name + " 过大,请选择"+this.settings.file_size_limit+"以内的文件进行上传."); //this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: progress.setStatus("Cannot upload Zero Byte files."); art.dialog.alert("请选择大于0KB,小于"+this.settings.file_size_limit+"的文件进行上传."); //this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: progress.setStatus("Invalid File Type."); art.dialog.alert("请选择类型为 "+this.settings.file_types_description+" 的文件进行上传."); //this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; default: if (file !== null) { progress.setStatus("Unhandled Error"); } //this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; } } catch (ex) { // this.debug(ex); art.dialog.error("上传文件失败,请刷新页面后重试."); } }, upload_start_handler : function (file) { try { //完成上传前的最后验证以及其他你需要的操作,例如添加、修改、删除post数据等。 var progress = new FileProgress(file, this.customSettings.progressTarget); progress.setStatus("Uploading..."); progress.toggleCancel(true, this); if (self.settings.showTip) { if (!SRM_SWFUpload.uploadTip) { SRM_SWFUpload.uploadTip = //art.dialog.tips('正在上传文件 '+file.name+' ,请稍等...', 60); self.uploadTips('正在上传文件 '+file.name+' ,请稍等...'); } else { SRM_SWFUpload.uploadTip.content('正在上传文件 '+file.name+' ,请稍等...').title('上传中...').show(); } } } catch (ex) { } return true; }, // upload_progress_handler : function (file, bytesLoaded, bytesTotal) { // try { // var percent = Math.ceil((bytesLoaded / bytesTotal) * 100); // var progress = new FileProgress(file, this.customSettings.progressTarget); // progress.setProgress(percent); // progress.setStatus("Uploading..."); // $(document.body).prepend(percent); // } catch (ex) { // this.debug(ex); // } // }, upload_error_handler : function (file, errorCode, message) { var progress = new FileProgress(file, this.customSettings.progressTarget); progress.setError(); progress.toggleCancel(false); switch (errorCode) { case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: progress.setStatus("Upload Error: " + message); art.dialog.alert("文件 " + file.name + " 上传失败. 网络错误."+message); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: progress.setStatus("Upload Failed."); this.debug("文件 " + file.name + " 尺寸过大. " + file.size + ", 请重新选择."+message); break; case SWFUpload.UPLOAD_ERROR.IO_ERROR: progress.setStatus("Server (IO) Error"); art.dialog.alert("Error Code: IO Error, File name: " + file.name + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: progress.setStatus("Security Error"); art.dialog.alert("Error Code: Security Error, File name: " + file.name + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: progress.setStatus("Upload limit exceeded."); art.dialog.alert("文件队列已满,文件 " + file.name + " 上传失败. " + message); break; case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED: progress.setStatus("Failed Validation. Upload skipped."); art.dialog.alert("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: // If there aren't any files left (they were all cancelled) disable the cancel button if (this.getStats().files_queued === 0) { document.getElementById(this.customSettings.cancelButtonId).disabled = true; } progress.setStatus("Cancelled"); progress.setCancelled(); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: progress.setStatus("Stopped"); break; default: progress.setStatus("Unhandled Error: " + errorCode); art.dialog.alert("未知错误,错误代码 " + errorCode + ", 文件 " + file.name + ", File size: " + file.size + ", Message: " + message); break; } }, upload_success_handler : function (file, serverData) { /* * 注意不能 * this.cancelUpload(); * 不然导致 * 一个上传完成(发送file信息,并返回200状态时调用此方法)后, * 取消只会取消当前文件的上传,而不是取消整个队列上传,所以每隔一个就会被取消 * 这个upload_success_handler每个文件上传完成都会调用一次,一个文件上传周期没有完成,还会触发upload_complete_handler;uploadComplete(file) * */ if (serverData != null && serverData != ""){ try { file.id = "singlefile"; var progress = new FileProgress(file, this.customSettings.progressTarget); progress.setComplete(); progress.setStatus("Complete."); progress.toggleCancel(false); var _uploadFileName = $("#"+self.contextName+self.settings.uploadFileName); _uploadFileName.val(self.SWF_SELECT_FILE_NAME); var _picturePath = $("#"+self.contextName+self.settings.picturePath); _picturePath.val(_picturePath.val() + serverData+SRM_SWFUpload.SPLITE); var _pictureSize = $("#"+self.contextName+self.settings.pictureSize); _pictureSize.val(_pictureSize.val() + file.size+SRM_SWFUpload.SPLITE); var _biddingFileId = $("#"+self.biddingFileId); _biddingFileId.append(file.name + SRM_SWFUpload.SPLITE); } catch (e) { alert("upload_success_handler"+e); } } }, upload_complete_handler : function (file) { //("上传完成");,不一定是上传成功 if (this.getStats().files_queued === 0) { // 队列文件全部上传完成 document.getElementById(this.customSettings.cancelButtonId).disabled = true; // 判断队列没有文件,关闭上传tip if (self.settings.showTip) { if (SRM_SWFUpload.uploadTip){ SRM_SWFUpload.uploadTip.content('上传完成.'); SRM_SWFUpload.uploadTip.title('完成'); SRM_SWFUpload.uploadTip.hide(); // SRM_SWFUpload.uploadTip.button( // { // name: '确定', // callback: function () { // this.hide(); // }, // disabled: false // } // ) self.uploadCompleteTip('上传完成.'); } } var _uploadFileName = $("#"+self.contextName+self.settings.uploadFileName); _uploadFileName.val(self.getLastSplitStr(_uploadFileName.val(), SRM_SWFUpload.SPLITE)); var _picturePath = $("#"+self.contextName+self.settings.picturePath); _picturePath.val(self.getLastSplitStr(_picturePath.val(), SRM_SWFUpload.SPLITE)); var _pictureSize = $("#"+self.contextName+self.settings.pictureSize); _pictureSize.val(self.getLastSplitStr(_pictureSize.val(), SRM_SWFUpload.SPLITE)); var _biddingFileId = $("#"+self.biddingFileId); _biddingFileId.html(self.getLastSplitStr(_biddingFileId.html(), SRM_SWFUpload.SPLITE)); $("#"+self.delFileButtonId).html("删除"); self.SWF_SELECT_FILE_NAME = ''; } }, swfupload_loaded_handler: function () { // ready } }; this.swfuObject = new SWFUpload(_swfSet); this.addToList(this.prefixName, this.swfuObject); }, generateHTML : function (divObj){ var self = this; var divHtml = [ // fsUploadProgress '<div style="display:none;" id="'+this.progressTarget+'" ></div>', '<div style="display:none;" id="'+this.divStatusId+'divStatus" ></div>', '<div style="height:28px;">', '<div style="float:left;padding-top:5px">', '<a href="javascript:void(0);">', '<span id="'+this.biddingFileId+'">'+this.settings.uploadFileNameVal+'</span>', '</a>', '<a style="padding-left:10px;padding-right:5px;" href="javascript:void(0);" id="'+this.delFileButtonId+'"></a>', '</div>', '<div style="" id="'+this.buttonId+'"></div>', '<input id="'+this.cancelButtonId+'" type="button" value="Cancel All Uploads" disabled="disabled" style="display:none;"/>', '<span id="'+this.prefixName+'desc">'+this.settings.descInfo+'</span>', // 五个隐藏域 '<input name="'+this.settings.appendixId+'" id="'+this.contextName+this.settings.appendixId+'" type="hidden" value="'+this.settings.appendixIdVal+'"/>', '<input name="'+this.settings.uploadFileName+'" id="'+this.contextName+this.settings.uploadFileName+'" type="hidden" value="'+this.settings.uploadFileNameVal+'"/>', '<input name="'+this.settings.oldPath+'" id="'+this.contextName+this.settings.oldPath+'" type="hidden" value="'+this.settings.oldPathVal+'"/>', '<input name="'+this.settings.picturePath+'" id="'+this.contextName+this.settings.picturePath+'" type="hidden" value="'+this.settings.picturePathVal+'"/>', '<input name="'+this.settings.pictureSize+'" id="'+this.contextName+this.settings.pictureSize+'" type="hidden" value="'+this.settings.pictureSizeVal+'"/>', '</div>', ''].join(""); divObj.html(divHtml); $("#"+self.biddingFileId).parent().click( function () { self.downFile('down_file'); }); $("#"+self.delFileButtonId).click( function () { self.delFile('del_file'); }); return divHtml; }, downFile:function (handleName) { this.queueEvent(handleName, $("#"+this.contextName+this.settings.picturePath).val()); }, delFile:function (handleName, id) { // this.queueEvent(handleName, id); var picturePath = $("#"+this.contextName+this.settings.picturePath).val(); // del临时文件 $("#"+this.biddingFileId).html(""); $("#"+this.contextName+this.settings.uploadFileName).val(""); $("#"+this.contextName+this.settings.picturePath).val(""); $("#"+this.contextName+this.settings.pictureSize).val(""); $("#"+this.biddingFileId).html(""); $("#"+this.delFileButtonId).html(""); // 删除临时路径的文件 $.ajax({ url:'../upload/delTempFile.action', type : "POST", data:{'fileUrl':picturePath}, timeout : 120000, cache : false, success:function (data) { try { //var json = $.parseJSON(data); } catch (e) { } }, error:function(){ } }); }, queueEvent:function (handlerName, argumentArray) { // 加入队列事件 // window.open("../upload/download.action?fileUrl=" + $("#"+this.settings.picturePathVal).val()); if (argumentArray == undefined) { argumentArray = []; } else if (!(argumentArray instanceof Array)) { argumentArray = [argumentArray]; } var self = this; if (typeof this.settings[handlerName] === "function") { // Queue the event this.eventQueue.push(function () { this.settings[handlerName].apply(this, argumentArray); }); // Execute the next queued event setTimeout(function () { self.executeNextEvent(); }, 0); } else if (this.settings[handlerName] !== null) { throw "Event handler '" + handlerName + "' is unknown or is not a function"; } }, executeNextEvent : function () { var f = this.eventQueue ? this.eventQueue.shift() : null; if (typeof(f) === "function") { f.apply(this); } }, addToList:function (swfuName, swfuObj) { // 属性名 = 属性值 return SRM_SWFUpload.uploadList[swfuName] = swfuObj; }, getSwfu:function (swfId) { return this.swfuObject; }, getAppendixId:function () { return $("#"+this.contextName+this.settings.appendixId).val(); }, getUploadFileName:function () { return $("#"+this.contextName+this.settings.uploadFileName).val(); }, getPicturePath:function () { return $("#"+this.contextName+this.settings.picturePath).val(); }, getPictureSize:function () { return $("#"+this.contextName+this.settings.pictureSize).val(); }, destroy : function() { this.swfuObject.destroy(); }, cancle : function() { this.swfuObject.cancelQueue(); }, uploadTips :function (content, title) { if (SRM_SWFUpload.ART_DIALOG_VER == '4.1.2') { return art.dialog({ title:title?title:'上传中...', content: content, fixed: true, resize: false, drag: true , width:'250', ok:false, esc:false, cancel:false }); } else { return art.dialog({ title:title?title:'上传中...', content: content, fixed: true, resize: false, drag: true , width:'250', yesFn:false, noFn:false, esc:false // , // button: [ // { // name: '确定', // disabled: true // } // ] }); } }, uploadCompleteTip :function (content, title) { return art.dialog({ title:title?title:'上传完成', content: content, icon: 'succeed', fixed: true, resize: false, drag: true , width:'250', esc:false }).show(); }, getSplitePostion : function (str, sIndex, splite, count) { /* * str 从sIndex开始到splite第count出现的位置 之间的位置 * 超过最大出现次数,返回最后一次出现的位置 * substring包括开始,不包括结束 */ // count不能超过总次数 var tsrc = str.substring(sIndex); var acount = this.getCountInstances(tsrc, splite); if (count > acount) { // 超过返回最后一次出现的次数 return this.getSplitePostion(tsrc, 0, splite, acount); } // str: 是你的原字符串 // splite: 是你的要找的字符串 // count: 寻找的次数 var re = new RegExp(splite,"g"); while(count--){ re.test(tsrc); } var pos = re.lastIndex-splite.length; if (pos < 0) return -1; else return pos; }, getSplitStr : function (str, sIndex, splite, count) { /* * str 从sIndex开始到splite第count出现的位置 之间的 的字符串 * substring包括开始,不包括结束 */ var pos = this.getSplitePostion(str, sIndex, splite, count); if (pos < 0){ // 没有找到 return ''; } else { return str.substring(sIndex, pos); } }, getCountInstances : function (mainStr, subStr){ // 字符串在mainstr中出现的次数 var count = 0; var offset = 0; do { offset = mainStr.indexOf(subStr, offset); if(offset != -1) { count++; offset += subStr.length; } } while(offset != -1) return count; }, getLastSplitStr : function (str, split) { // 字符串split在源str最后出现的位置 之间的str return this.getSplitStr(str, 0, split, this.getCountInstances(str, split)); } }; SRM_SWFUpload.movieCount = 0; SRM_SWFUpload.version = "1.1.0 2013-12-05"; SRM_SWFUpload.uploadList = {}; SRM_SWFUpload.uploadTip ; SRM_SWFUpload.add = function(n, o){ return SRM_SWFUpload.uploadList[n] = o; }; SRM_SWFUpload.get = function (id) { return SRM_SWFUpload.uploadList[id]; }; SRM_SWFUpload.destroy = function(id) { if (!id || id == undefined || id == null || id == "") { for(var o in SRM_SWFUpload.uploadList){ SRM_SWFUpload.uploadList[o].destroy(); if (document.getElementById(o)) { document.getElementById(o).innerHTML = ''; } } } else { SRM_SWFUpload.uploadList[id].destroy(); if (document.getElementById(id)) { document.getElementById(id).innerHTML = ''; } } }; })(jQuery);
?后台获取filePostName参数值,即可,
FileOutputStream fos; fos = new FileOutputStream(this.getRequest().getSession().getServletContext().getRealPath( Constants.SPRIT) + fileSaveUrl); // 以上传文件建立一个文件上传流 FileInputStream fis = new FileInputStream(getUpload()); // 将上传文件的内容写入服务器 byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); fis.close(); this.getResponse().getWriter().print(fileSaveUrl);
?fileSaveUrl为返回值,windows下必须返回值不为空,否则不会触发uploadSuccess事件
?
?
HTML调用,如下
$(id).swfuInit({ // 自定义参数值 });
?