1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > step-by-step多文件WEB批量上传(swfupload)的完美解决方案

step-by-step多文件WEB批量上传(swfupload)的完美解决方案

时间:2020-10-22 06:06:31

相关推荐

step-by-step多文件WEB批量上传(swfupload)的完美解决方案

来源:/goody9807/archive//11/04/1326098.html

功能完全支持ie和firefox浏览器!

一般的WEB方式文件上传只能一个一个的进行上传,在某些应用上就显得很不人性化,客户们都希望能够1次选择很多文件,然后让系统把选择的文件全部上传。

这里,就将针对这个问题提出一个比较完美的解决方案,利用的技术主要有2个:Flash 和 smartupload。Flash 能够让客户一次选择多个文件,而smartupload负责将选择的文件上传到服务器上。

有些朋友看到这里,就知道了,其实就是swfupload方法,具体信息可以访问swfupload官方网站:/

让我们先来看看客户端的界面效果图。(多选文件,批量上传,上传进度显示)

要做到图中的效果,其实很方便,看完下面的描述,相信大家都可以实现上图中的效果了。

说明:swfupload2中通过一个png图片与flash插件进行关联,可以修改images下的png图片来(如上图中的[选择文件]图片)自定义显示自己想要的图片样子(不要修改图片名字和格式)。

如果你用的不是java环境,不要紧,只要稍作修改,同样可以使用在其他的环境中。

第1步,要进行下面的过程,必须先准备好Flash插件和smartupload。

Flash插件:相信大家的浏览器早已经安装过了,请检查版本,尽量使用最新的的flash插件。

smartupload:大家可以去看看我的另一篇文章 [上传下载组件SmartUpload使用方法] /blog/255010 里面详细讲述了使用方法,并且提供了具体java类的下载。请先熟悉smartupload,然后再开始下面的步骤。

第2步,前台部分准备客户操作的WEB界面,如下[UploadFileExample.jsp、UploadFileExampleSubmit.jsp]

(关于参数 upload_url: "<%=uploadUrl.toString()%>",

要注意提交文件路径,最好用http://.../UploadFileExample.jsp格式的完整路径,即像我例子中写的那样)

UploadFileExample.jsp

Html代码< %@pagecontentType ="text/html;charset=UTF-8" %> < % doubleperMaxSize =1 .5;//单个文件允许的max大小 StringsizeUnit ="MB" ;//perMaxSize数据对应的单位 Stringext ="*.jpg;*.jpeg;*.gif" ;//允许上传的文件类型 //文件上传提交的目标页面 StringBufferuploadUrl =new StringBuffer("http://"); uploadUrl.append(request.getHeader("Host")); uploadUrl.append(request.getContextPath()); uploadUrl.append("/admin/swfuploadexample/UploadFileExampleSubmit.jsp"); %> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> < html > < head > < title > 批量相片上传</ title > < meta http-equiv ="Content-Type" content ="text/html;charset=UTF-8" > < link href ="css/default.css" rel ="stylesheet" type ="text/css" /> < script type ="text/javascript" src ="js/swfupload.js" > </ script > < script type ="text/javascript" src ="js/swfupload.swfobject.js" > </ script > < script type ="text/javascript" src ="js/swfupload.queue.js" > </ script > < script type ="text/javascript" src ="js/fileprogress.js" > </ script > < script type ="text/javascript" src ="js/handlers.js" > </ script > < script type ="text/javascript" > varswfu; SWFUpload.onload =function (){ varsettings ={ flash_url:"js/swfupload.swf", upload_url:"< %=uploadUrl.toString()%> ", post_params:{ "user_id":"stephen830", "pass_id":"123456" }, file_size_limit:"< %=perMaxSize%> < %=sizeUnit%> ", file_types:"< %=ext%> ", file_types_description:"< %=ext%> ", file_upload_limit:100, file_queue_limit:0, custom_settings:{ progressTarget:"fsUploadProgress", cancelButtonId:"btnCancel", uploadButtonId:"btnUpload", myFileListTarget:"idFileList" }, debug:false, auto_upload:false, //ButtonSettings button_image_url:"images/XPButtonUploadText_61x22.png",//RelativetotheSWFfile button_placeholder_id:"spanButtonPlaceholder", button_width:61, button_height:22, //Theeventhandlerfunctionsaredefinedinhandlers.js swfupload_loaded_handler:swfUploadLoaded, file_queued_handler:fileQueued, file_queue_error_handler:fileQueueError, file_dialog_complete_handler:fileDialogComplete, upload_start_handler:uploadStart, upload_progress_handler:uploadProgress, upload_error_handler:uploadError, upload_success_handler:uploadSuccess, upload_complete_handler:uploadComplete, queue_complete_handler:queueComplete,//Queuepluginevent //SWFObjectsettings minimum_flash_version:"9.0.28", swfupload_pre_load_handler:swfUploadPreLoad, swfupload_load_failed_handler:swfUploadLoadFailed }; swfu =new SWFUpload(settings); } </ script > </ head > < body bgcolor ="#FCFCFC" topmargin ="0px" leftmargin ="10px" rightmargin ="10px" scroll ="yes" > < table width ="100%" cellspacing ="4" cellpadding ="4" border ="0" bgcolor ="#FCFCFC" > < tr > < td class ="DH1" > < table width ="100%" cellspacing ="4" cellpadding ="4" border ="0" bgcolor ="#FCFCFC" > < tr > < td class ="DH2" > < STRONG > 批量上传相片(支持的相片类型:< %=ext%> ;单个相片最大不能超过:< %=perMaxSize%> < %=sizeUnit%> )</ STRONG > </ td > < td class ="DH2" align ="right" > </ td > </ tr > </ table > < div id ="content" > < form id ="form1" action ="UploadFileExampleSubmit.jsp" method ="post" enctype ="multipart/form-data" > < table width ="90%" cellspacing ="0" cellpadding ="0" border ="0" > < tr > < td > < span id ="spanButtonPlaceholder" > </ span > < input id ="btnUpload" type ="button" value ="上传相片" class ="btn" /> < input id ="btnCancel" type ="button" value ="取消全部上传" disabled ="disabled" class ="btn" /> </ td > </ tr > </ table > < table id ="idFileList" class ="uploadFileList" > < tr class ="uploadTitle" > < td > < B > 文件名</ B > </ td > < td > < B > 文件大小</ B > </ td > < td width =100px > < B > 状态</ B > </ td > < td width =35px > &nbsp;</ td > </ tr > </ table > 等待上传< span id ="idFileListCount" > 0</ span > 个,成功上传< span id ="idFileListSuccessUploadCount" > 0</ span > 个 < div id ="divSWFUploadUI" style ="visibility:hidden;" > </ div > < noscript style ="display:block;margin:10px25px;padding:10px15px;" > 很抱歉,相片上传界面无法载入,请将浏览器设置成支持JavaScript。 </ noscript > < div id ="divLoadingContent" class ="content" style ="background-color:#FFFF66;border-top:solid4px#FF9966;border-bottom:solid4px#FF9966;margin:10px25px;padding:10px15px;display:none;" > 相片上传界面正在载入,请稍后... </ div > < div id ="divLongLoading" class ="content" style ="background-color:#FFFF66;border-top:solid4px#FF9966;border-bottom:solid4px#FF9966;margin:10px25px;padding:10px15px;display:none;" > 相片上传界面载入失败,请确保浏览器已经开启对JavaScript的支持,并且已经安装可以工作的Flash插件版本。 </ div > < div id ="divAlternateContent" class ="content" style ="background-color:#FFFF66;border-top:solid4px#FF9966;border-bottom:solid4px#FF9966;margin:10px25px;padding:10px15px;display:none;" > 很抱歉,相片上传界面无法载入,请安装或者升级您的Flash插件。 请访问:< a href ="/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target ="_blank" > Adobe网站</ a > 获取最新的Flash插件。 </ div > </ form > </ div > </ td > </ tr > </ table > </ body > </ html >

<%@ page contentType="text/html;charset=UTF-8"%><%double perMaxSize = 1.5;//单个文件允许的max大小String sizeUnit = "MB";//perMaxSize数据对应的单位String ext = "*.jpg;*.jpeg;*.gif";//允许上传的文件类型//文件上传提交的目标页面StringBuffer uploadUrl = new StringBuffer("http://");uploadUrl.append(request.getHeader("Host"));uploadUrl.append(request.getContextPath());uploadUrl.append("/admin/swfuploadexample/UploadFileExampleSubmit.jsp");%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>批量相片上传</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link href="css/default.css" rel="stylesheet" type="text/css" /><script type="text/javascript" src="js/swfupload.js"></script><script type="text/javascript" src="js/swfupload.swfobject.js"></script><script type="text/javascript" src="js/swfupload.queue.js"></script><script type="text/javascript" src="js/fileprogress.js"></script><script type="text/javascript" src="js/handlers.js"></script><script type="text/javascript">var swfu;SWFUpload.onload = function () {var settings = {flash_url : "js/swfupload.swf",upload_url: "<%=uploadUrl.toString()%>",post_params: {"user_id" : "stephen830","pass_id" : "123456"},file_size_limit : "<%=perMaxSize%> <%=sizeUnit%>",file_types : "<%=ext%>",file_types_description : "<%=ext%>",file_upload_limit : 100,file_queue_limit : 0,custom_settings : {progressTarget : "fsUploadProgress",cancelButtonId : "btnCancel",uploadButtonId : "btnUpload",myFileListTarget : "idFileList"},debug: false,auto_upload:false,// Button Settingsbutton_image_url : "images/XPButtonUploadText_61x22.png",// Relative to the SWF filebutton_placeholder_id : "spanButtonPlaceholder",button_width: 61,button_height: 22,// The event handler functions are defined in handlers.jsswfupload_loaded_handler : swfUploadLoaded,file_queued_handler : fileQueued,file_queue_error_handler : fileQueueError,file_dialog_complete_handler : fileDialogComplete,upload_start_handler : uploadStart,upload_progress_handler : uploadProgress,upload_error_handler : uploadError,upload_success_handler : uploadSuccess,upload_complete_handler : uploadComplete,queue_complete_handler : queueComplete,// Queue plugin event// SWFObject settingsminimum_flash_version : "9.0.28",swfupload_pre_load_handler : swfUploadPreLoad,swfupload_load_failed_handler : swfUploadLoadFailed};swfu = new SWFUpload(settings);}</script></head><body bgcolor="#FCFCFC" topmargin="0px" leftmargin="10px" rightmargin="10px" scroll="yes"><table width="100%" cellspacing="4" cellpadding="4" border="0" bgcolor="#FCFCFC"><tr><td class="DH1"><table width="100%" cellspacing="4" cellpadding="4" border="0" bgcolor="#FCFCFC"><tr><td class="DH2"><STRONG>批量上传相片 (支持的相片类型:<%=ext%>;单个相片最大不能超过:<%=perMaxSize%> <%=sizeUnit%>)</STRONG></td><td class="DH2" align="right"></td></tr></table><div id="content"><form id="form1" action="UploadFileExampleSubmit.jsp" method="post" enctype="multipart/form-data"><table width="90%" cellspacing="0" cellpadding="0" border="0"><tr><td><span id="spanButtonPlaceholder"></span><input id="btnUpload" type="button" value="上传相片" class="btn" /><input id="btnCancel" type="button" value="取消全部上传" disabled="disabled" class="btn" /></td></tr></table><table id="idFileList" class="uploadFileList"><tr class="uploadTitle"><td><B>文件名</B></td><td><B>文件大小</B></td><td width=100px><B>状态</B></td><td width=35px>&nbsp;</td></tr></table>等待上传 <span id="idFileListCount">0</span> 个 ,成功上传 <span id="idFileListSuccessUploadCount">0</span> 个<div id="divSWFUploadUI" style="visibility: hidden;"></div><noscript style="display: block; margin: 10px 25px; padding: 10px 15px;">很抱歉,相片上传界面无法载入,请将浏览器设置成支持JavaScript。</noscript><div id="divLoadingContent" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">相片上传界面正在载入,请稍后...</div><div id="divLongLoading" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">相片上传界面载入失败,请确保浏览器已经开启对JavaScript的支持,并且已经安装可以工作的Flash插件版本。</div><div id="divAlternateContent" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">很抱歉,相片上传界面无法载入,请安装或者升级您的Flash插件。请访问: <a href="/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank">Adobe网站</a> 获取最新的Flash插件。</div></form></div></td></tr></table></body></html>

UploadFileExample.jsp对应的处理页面 --> UploadFileExampleSubmit.jsp

(1)请确保已经看完我的另一篇文章(上传下载组件SmartUpload使用方法 /admin/blogs/255010 ),先搞好这个才能开始下面的操作

(2)写一个对应上传方法类,com.soft4j.bo.PhotoMgr.java,其中的方法就是文章下面提到的public static String fileUpload(SmartUpload su,PageContext pageContext) throws Exception {...}

这2点弄好了,ok,可以继续。(如果没有准备java文件,下面的UploadFileExampleSubmit.jsp会报错)

注意在(UploadFileExampleSubmit.jsp)中:上传成功后必须返回“successed”,失败的话则返回失败的原因。

Html代码< %@pagecontentType ="text/html;charset=UTF-8" %> < %@pageimport ="com.soft4j.httpupload4j.SmartUpload" %> < %@pageimport ="com.soft4j.bo.PhotoMgr" %> < % StringpageErrorInfo =null ; SmartUploadsu =null ; try{ su =new SmartUpload(); su.initialize(pageContext); su.upload(); pageErrorInfo =PhotoMgr .fileUpload(su,pageContext); if(pageErrorInfo ==null){ out.print("successed"); } }catch(Exceptione){ pageErrorInfo =e.getMessage(); }finally{ su =null ; if(pageErrorInfo!=null){ out.print(pageErrorInfo); } } %>

<%@ page contentType="text/html;charset=UTF-8"%><%@ page import="com.soft4j.httpupload4j.SmartUpload"%><%@ page import="com.soft4j.bo.PhotoMgr"%><%String pageErrorInfo = null;SmartUpload su = null;try{su = new SmartUpload();su.initialize(pageContext);su.upload();pageErrorInfo = PhotoMgr.fileUpload(su,pageContext);if(pageErrorInfo==null){out.print("successed");}}catch(Exception e){pageErrorInfo = e.getMessage();}finally{su = null;if(pageErrorInfo!=null){out.print(pageErrorInfo);}}%>

第3步 准备后台的文件上传功能。也就是上面文件[UploadFileExampleSubmit.jsp]中用到的[PhotoMgr.fileUpload(su,pageContext)]方法。

Java代码/** *文件上传方法. *@paramsu *@parampageContext *@return *@throwsException */ public static StringfileUpload(SmartUploadsu,PageContextpageContext)throws Exception{ com.soft4j.httpupload4j.FilesuFile=null ; int fileCount=0 ; try { //获取传递过来的参数 StringuserId=su.getRequest().getParameter("user_id" ); StringpassId=su.getRequest().getParameter("pass_id" ); StringfileExt="" ; int fileSize=0 ; StringAllowedExtensions=",jpg,jpeg,gif," ;//允许上传的文件类型 double maxFileSize=1.5 *1024 ;//单文件最大大小,单位KB //校验文件类型和大小 for (int i=0 ;i<su.getFiles().getCount();i++){ suFile=su.getFiles().getFile(i); if (suFile.isMissing()) continue ; //校验文件大小 fileSize=suFile.getSize()/1024 ;//字节转换成KB if (fileSize==0 )fileSize=1 ; if (maxFileSize<fileSize)throw new Exception("单个上传相片的容量不能超过[" +maxFileSize+"KB]" ); //校验文件类型 if (suFile.getFileExt()==null ||"" .equals(suFile.getFileExt())){ fileExt=",," ; }else { fileExt="," +suFile.getFileExt().toLowerCase()+"," ; } if (!"" .equals(AllowedExtensions) &&AllowedExtensions.indexOf(fileExt)==-1 ){ throw new Exception("您上传的文件[" +suFile.getFileName() +"]的类型为系统禁止上传的文件类型,不能上传!" ); } fileCount++; } if (fileCount==0 )throw new Exception("请选择上传的文件" ); //准备保存文件 StringfilePath="D://tomcat//webapps//test//photo//" ;//这里填写项目中存放上传文件的物理路径 for (int i=0 ;i<su.getFiles().getCount();i++){ suFile=su.getFiles().getFile(i); suFile.saveAs(filePath+suFile.getFileName(),SmartUpload.SAVE_PHYSICAL);//保存文件 } //成功返回null return null ; }finally { // } }

/*** 文件上传方法.* @param su* @param pageContext* @return* @throws Exception*/public static String fileUpload(SmartUpload su,PageContext pageContext) throws Exception {com.soft4j.httpupload4j.File suFile = null;int fileCount = 0;try {//获取传递过来的参数String userId = su.getRequest().getParameter("user_id");String passId = su.getRequest().getParameter("pass_id");String fileExt = "";int fileSize = 0;String AllowedExtensions = ",jpg,jpeg,gif,";//允许上传的文件类型double maxFileSize = 1.5*1024;//单文件最大大小,单位KB//校验文件类型和大小for (int i=0; i<su.getFiles().getCount();i++) {suFile = su.getFiles().getFile(i);if (suFile.isMissing())continue;//校验文件大小fileSize = suFile.getSize()/1024;//字节转换成KBif(fileSize==0) fileSize=1;if(maxFileSize<fileSize) throw new Exception("单个上传相片的容量不能超过["+maxFileSize+"KB]");//校验文件类型if (suFile.getFileExt() == null|| "".equals(suFile.getFileExt())) {fileExt = ",,";} else {fileExt = "," + suFile.getFileExt().toLowerCase() + ",";}if (!"".equals(AllowedExtensions)&& AllowedExtensions.indexOf(fileExt) == -1) {throw new Exception("您上传的文件[" + suFile.getFileName()+ "]的类型为系统禁止上传的文件类型,不能上传!");}fileCount++;}if (fileCount==0) throw new Exception("请选择上传的文件");//准备保存文件String filePath="D://tomcat//webapps//test//photo//";//这里填写项目中存放上传文件的物理路径for (int i=0; i<su.getFiles().getCount();i++) {suFile = su.getFiles().getFile(i);suFile.saveAs(filePath+suFile.getFileName(),SmartUpload.SAVE_PHYSICAL);//保存文件}//成功返回nullreturn null;} finally {//}}

备注:关于jsp页面和java方法我不做过多的说明了,应该已经比较清楚了。

附录:swfupload 文件批量上传压缩包 swfupload.zip(支持最新的flash10插件)(附件中没有java类,请自己准备1个java类,将上面的方法复制进去)

下载:

/topics/download/58bc72da-1c10-341f-ae10-2d27b74f64bc

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。