`

SWFUpload V2.2.0 DEMO解析

 
阅读更多
<style type="text/css"> <!-- @page {margin:2cm} p {margin-bottom:0.21cm} a:link {color:#0000ff} --> </style>

SWFUpload

SWF多文件无刷新上传,利用flash完成多文件上传操作。服务器端可以用StrutsServletJSP完成,这里用Struts1.x完成上传

  1. 首先看下目录结构




SWFUpload这个文件夹是核心文件,里面的文件一个都不能少。

css文件夹是样式文件,所有的样式可以在此文件中修改完成

images是图片

jslibjs库文件,需要的上传的js文件和flash文件


其中handlers.js是上传中一系列的事件,可以在此文件中修改自己的上传所需要的事件。如开始上传、取消、停止上传等


swfupload.queue.js这个文件主要是完成将客户端选择的多一个文件一个个的排成一个队列,然后依次向服务器上传。

swfupload.swfflash文件,就那个添加或上传的按钮

sample.html是完成后的上传实例



  1. 首先看看客户端的sample.html中的jshtml内容

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN">

<html>

<head>

<title>SWFUpload多文件上传示例</title>

<metahttp-equiv="content-type"content="text/html;charset=gbk">

<linkrel="stylesheet"type="text/css"href="css/default.css">

<scripttype="text/javascript"src="jslib/swfupload.js"></script>

<scripttype="text/javascript"src="jslib/swfupload.queue.js"></script>

<scripttype="text/javascript"src="jslib/fileprogress.js"></script>

<scripttype="text/javascript"src="jslib/handlers.js"charset="utf-8"></script>

<scripttype="text/javascript">

varswfUpload;

window.onload=function(){

varsettings={

flash_url:"jslib/swfupload.swf",

upload_url:"../upload.do",

post_params:{"param":"uploadParams"},

file_size_limit:"200MB",

file_types:"*.*",

file_post_name:"uploadFile",

file_types_description:"AllFiles",

file_upload_limit: 50,

file_queue_limit: 0,

custom_settings:{

progressTarget:"fsUploadProgress",

cancelButtonId:"btnCancel"

},

debug:true,//是否显示调试的textarea

//Buttonsettings

button_image_url:"images/TestImageNoText_65x29.png",

button_width:"65",

button_height:"29",

button_placeholder_id:"spanButtonPlaceHolder",

button_text:'<spanclass="theFont"></span>',

button_text_style:".theFont{font-size:12;}",

button_text_left_padding:12,

button_text_top_padding:3,


//Theeventhandlerfunctionsaredefinedinhandlers.js

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

};

//自定义属性,是否停止上传

swfUpload=newSWFUpload(settings);

swfUpload.stopped=false;

};


functionfileDialogComplete(numberselected,numberqueued){

if(swfUpload.getStats().files_queued>0){

document.getElementById("btnCancel").disabled=false;

}

}



functionqueueComplete(numberselected,numberqueued){

//alert(numberselected+"-"+numberqueued);

}


functionupload(){

if(swfUpload.getStats().files_queued>0){

//document.getElementById("btnCancel").disabled=true;

swfUpload.startUpload();

}else{

alert("请选择要上传的文件!");

}

}

functionstop(){

if(swfUpload){

swfUpload.stopUpload();

}

}

</script>

</head>

<body>

<divid="content">

<h2></h2>

<formid="form1"action=""method="post"enctype="multipart/form-data">

<p></p>

<divclass="fieldsetflash"id="fsUploadProgress">

<spanclass="legend">上传文件列表</span>

</div>

<divid="divMovieContainer">

<inputid="filenamelist"type="hidden"name="filenamelist"/>

<spanid="spanButtonPlaceHolder"></span>

<inputtype="button"value=""onclick="upload();"style="margin-left:2px;font-size:8pt;height:29px;"/>

<inputtype="button"value=""onclick="stop();"style="display:none;margin-left:2px;font-size:8pt;height:29px;"/>

<inputid="btnCancel"type="button"value="取消所有"onclick="swfUpload.cancelQueue();"disabled="disabled"style="margin-left:2px;font-size:8pt;height:29px;"/>

<inputtype="button"onclick="javaScript:window.close();"name="bt"style="margin-left:2px;font-size:8pt;height:29px;"value=""/>

</div>

</form>

</div>

</body>

</html>

A.先介绍导入的js文件

<linkrel="stylesheet"type="text/css"href="css/default.css">

<scripttype="text/javascript"src="jslib/swfupload.js"></script>

<scripttype="text/javascript"src="jslib/swfupload.queue.js"></script>

<scripttype="text/javascript"src="jslib/fileprogress.js"></script>

<scripttype="text/javascript"src="jslib/handlers.js"charset="utf-8"></script>

这些文件是必须的,且在导入的时候注意你的路径和顺序。还有就文件编码,文件保存的不同编码可以会影响文件显示的乱码问题,charset就是文件保存的编码。

B.然后在其中是script脚本的参数详细讲解

设置flash文件

flash_url:"jslib/swfupload.swf",

设置服务器的上传地址

upload_url:"../upload.do",

提交到服务器的参数信息,这样就添加了一个param参数,值是uploadParams在服务器端用request.getParameter(“param”)就可以拿到值

post_params:{"param":"uploadParams"},

上传文件的最大空间

file_size_limit:"200MB",

允许上传文件的类型*.*是所有,*.txt只能上传文本

file_types:"*.*",

这个就服务器端要获得的文件的属性,相当于filename

file_post_name:"uploadFile",

所有文件夹

file_types_description:"AllFiles",

上传文件选取的最大队列数

file_upload_limit: 50,

file_queue_limit:0,


下面是上传按钮的设置

button_image_url:"images/TestImageNoText_65x29.png",

button_width:"65",

button_height:"29",

button_placeholder_id:"spanButtonPlaceHolder",

button_text:'<spanclass="theFont"></span>',

button_text_style:".theFont{font-size:12;}",

button_text_left_padding:12,

button_text_top_padding:3,


下面是上传事件和函数

选择完文件后就触发

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


下面看看html代码:

<formid="form1"action=""method="post"enctype="multipart/form-data">

<p></p>

<divclass="fieldsetflash"id="fsUploadProgress">

<spanclass="legend">上传文件列表</span>

</div>

<divid="divMovieContainer">

<inputid="filenamelist"type="hidden"name="filenamelist"/>

<spanid="spanButtonPlaceHolder"></span>

<inputtype="button"value=""onclick="upload();"style="margin-left:2px;font-size:8pt;height:29px;"/>

<inputtype="button"value=""onclick="stop();"style="display:none;margin-left:2px;font-size:8pt;height:29px;"/>

<inputid="btnCancel"type="button"value="取消所有"onclick="swfUpload.cancelQueue();"disabled="disabled"style="margin-left:2px;font-size:8pt;height:29px;"/>

<inputtype="button"onclick="javaScript:window.close();"name="bt"style="margin-left:2px;font-size:8pt;height:29px;"value=""/>

</div>

</form>


值得介绍的是

<spanid="spanButtonPlaceHolder"></span>

这个span就会被flsah的浏览多代替,注意这里的id和上面jsbutton_placeholder_id是对应的


<inputtype="button"value=""onclick="upload();"style="margin-left:2px;font-size:8pt;height:29px;"/>

这个是上传按钮,点击上传就会执行upload这个js方法

<inputtype="button"value=""onclick="stop();"style="display:none;margin-left:2px;font-size:8pt;height:29px;"/>

这个是停止上传的,可以取消当前正在上传的文件,运行stop方法

<inputid="btnCancel"type="button"value="取消所有"onclick="swfUpload.cancelQueue();"disabled="disabled"style="margin-left:2px;font-size:8pt;height:29px;"/>

取消所有的队列文件


  1. 官方的handlers被修改的几个方法

选择文件后显示文件的大小

functionfileQueued(file){

try{

varprogress=newFileProgress(file,this.customSettings.progressTarget);

varsize=file.size;

varunit="B";

if(size>(1024*1024*1024)){

unit="GB";

size/=(1024*1024*1024);

}elseif(size>(1024*1021)){

unit="MB";

size/= (1024 * 1024);

}elseif(size>1024){

unit="KB";

size/= 1024;

}

progress.setStatus("<fontcolor='red'>"+size.toFixed(2)+""+unit+"</font>等待上传......");

progress.toggleCancel(true,this);


}catch(ex){

this.debug(ex);

}

}

显示当前文件上传进度的百分比

functionuploadProgress(file,bytesLoaded,bytesTotal){

try{

varpercent=Math.ceil((bytesLoaded/bytesTotal)*100);


varprogress=newFileProgress(file,this.customSettings.progressTarget);

progress.setProgress(percent);

progress.setStatus("已上传"+percent+"%......");

}catch(ex){

this.debug(ex);

}

}

获取服务器端上传后返回的信息

functionuploadSuccess(file,serverData){

try{

varprogress=newFileProgress(file,this.customSettings.progressTarget);

progress.setComplete();

vardata=eval("("+serverData+")");

if(data.success==0||data.success=="0"){

progress.setStatus("上传完成!");

}else{

progress.setError();

progress.setStatus("上传失败!"+data.message);

}

progress.toggleCancel(false);

}catch(ex){

this.debug(ex);

}

}


  1. 下面看看服务器端的上传代码

//上传文件保存路径

publicstaticStringpath="/upload/";

//定义可以上传文件的后缀数组,默认"*",代表所有

publicstaticString[]filePostfixs={"*"};

publicstaticString[]typeImages={"gif","jpeg","png","jpg","tif","bmp"};

publicstaticString[]typeOthers={"html","htm","doc","xls","txt","zip","rar","pdf","cll"};

//上传文件的最大长度

publicstaticlongmaxFileSize=1024*1024*2;//2M

//一次读取多少字节

publicstaticintbufferSize=1024*8;

privatefinalstaticvoidinit(){

if(bufferSize>Integer.MAX_VALUE){

bufferSize=1024*8;

}elseif(bufferSize<8){

bufferSize=8;

}

if(maxFileSize<1){

maxFileSize=1024*1024*1024*2L;

}elseif(maxFileSize>Long.MAX_VALUE){

maxFileSize=1024*1024*1024*2L;

}

}

/**

*<b>function:</b>根据传递InputStream,上传文件

*@createDateDec19,20108:53:12PM

*@paramisInputStream

*@paramfileName文件名

*@parampath保存路径

*@return上传状态

*@throwsException

*/

publicstaticUploadStateupload4Stream(InputStreamis,StringfileName,Stringpath)throwsException{

init();

UploadStatestate=UploadState.UPLOAD_FAILURE;

if(fileName==null&&"".equals(fileName)){

fileName=getRandomName(fileName);

}

OutputStreamos=null;

try{

path=getDoPath(path);

mkDir(path);

fileName=getBracketFileName(fileName,path);

os=newFileOutputStream(path+fileName);

intread=0;

byte[]buffer=newbyte[bufferSize];

while((read=is.read(buffer))!=-1){

os.write(buffer,0,read);

}

state=UploadState.UPLOAD_SUCCSSS;

}catch(FileNotFoundExceptione){

state=UploadState.UPLOAD_NOTFOUND;

throwe;

}catch(Exceptione){

state=UploadState.UPLOAD_FAILURE;

throwe;

}finally{

if(is!=null){

is.close();

}

if(os!=null){

os.flush();

os.close();

}

}

returnstate;

}

/**

*<b>function:</b>主要针对strutsFormFile进行文件上传

*@createDateOct9,201011:22:14PM

*@paramfileFormFile

*@parampath路径

*@returnUploadState是否上传成功

*@throwsException

*/

publicstaticUploadStateupload(FormFilefile,StringfileName,Stringpath)throwsException{

init();

UploadStatestate=UploadState.UPLOAD_FAILURE;

if(fileName==null&&"".equals(fileName)){

fileName= file.getFileName();

}

InputStreamis=null;

try{

longfileSize=file.getFileSize();

if(fileSize<=0){

state=UploadState.UPLOAD_ZEROSIZE;

}else{

if(fileSize<=maxFileSize){

is= file.getInputStream();

state=upload4Stream(is,fileName,path);

}else{

state=UploadState.UPLOAD_OVERSIZE;

}

}

}catch(FileNotFoundExceptione){

state=UploadState.UPLOAD_NOTFOUND;

throwe;

}catch(Exceptione){

state=UploadState.UPLOAD_FAILURE;

throwe;

}finally{

if(is!=null){

is.close();

}

}

returnstate;

}

/**

*<b>function:</b>struts上传文件,并根据传递的文件类型数组验证上传的文件是否合法

*@createDateOct10,20103:53:59PM

*@paramfileFormFile

*@parampath路径

*@paramallowTypes文件类型数组

*@returnUploadState是否上传成功

*@throwsException

*/

publicstaticUploadStateupload(FormFilefile,StringfileName,Stringpath,String[]allowTypes)throwsException{

UploadStatestate=UploadState.UPLOAD_FAILURE;

if(validTypeByName(file.getFileName(),allowTypes)){

state=upload(file,fileName,path);

}

returnstate;

}

upload4Stream是通过传递InputStream完成上传,这个方法不管是是FormFileFile还是其他的文件对象都可以完成上传。你也可以根据自己的需求进行二次封装完成上传。

上面的上传还用到了其他的验证、命名、路径等辅助方法,详细请看源代码。

验证文件名、类型

/**

*<b>function:</b>根据文件名和类型数组验证文件类型是否合法,flag是否忽略大小写

*@createDateOct10,201011:54:54AM

*@paramfileName文件名

*@paramallowTypes类型数组

*@paramflag是否获得大小写

*@return是否验证通过

*/

publicstaticbooleanvalidTypeByName(StringfileName,String[]allowTypes,booleanflag){

Stringsuffix=getType(fileName);

booleanvalid=false;

if(allowTypes.length>0&&"*".equals(allowTypes[0])){

valid=true;

}else{

for(Stringtype:allowTypes){

if(flag){//不区分大小写后缀

if(suffix!=null&&suffix.equalsIgnoreCase(type)){

valid=true;

break;

}

}else{//严格区分大小写

if(suffix!=null&&suffix.equals(type)){

valid=true;

break;

}

}

}

}

returnvalid;

}

/**

*<b>function:</b>根据文件名称和类型数组验证文件类型是否合法

*@createDateOct10,201010:27:17AM

*@paramfileName文件名

*@paramallowTypes文件类型数组

*@return是否合法

*/

publicstaticbooleanvalidTypeByName(StringfileName,String[]allowTypes){

returnvalidTypeByName(fileName,allowTypes,true);

}

/**

*<b>function:</b>根据后缀和类型数组验证文件类型是否合法,flag是否区分后缀大小写,true严格大小写

*@createDateOct10,201012:00:10PM

*@paramsuffix后缀名

*@paramallowTypes文件类型数组

*@paramflag是否区分大小写

*@return是否合法

*/

publicstaticbooleanvalidTypeByPostfix(Stringsuffix,String[]allowTypes,booleanflag){

booleanvalid=false;

if(allowTypes.length>0&&"*".equals(allowTypes[0])){

valid=true;

}else{

for(Stringtype:allowTypes){

if(flag){//不区分大小写后缀

if(suffix!=null&&suffix.equalsIgnoreCase(type)){

valid=true;

break;

}

}else{//严格区分大小写

if(suffix!=null&&suffix.equals(type)){

valid=true;

break;

}

}

}

}

returnvalid;

}

/**

*<b>function:</b>根据文件后缀名和类型数组,验证文件类型是否合法

*@createDateOct10,201010:25:32AM

*@paramsuffix后缀名

*@paramallowTypes类型数组

*@return是否合法

*/

publicstaticbooleanvalidTypeByPostfix(Stringsuffix,String[]allowTypes){

returnvalidTypeByPostfix(suffix,allowTypes,true);

}

/**

*<b>function:</b>验证当前后缀、文件类型是否是图片类型

*typeImages可以设置图片类型

*@createDateOct10,201012:17:18PM

*@paramsuffix验证文件的后缀

*@return是否合法

*/

publicstaticbooleanvalidTypeByPostfix4Images(Stringsuffix){

returnvalidTypeByPostfix(suffix,typeImages);

}

/**

*<b>function:</b>验证当前后缀、文件类型是否是非图片类型(常用办公文件类型)

*typeOthers可以设置文件类型

*@createDateOct10,201012:18:18PM

*@paramsuffix验证文件的后缀

*@return是否合法

*/

publicstaticbooleanvalidTypeByPostfix4Others(Stringsuffix){

returnvalidTypeByPostfix(suffix,typeOthers);

}

/**

*<b>function:</b>验证当前文件名、文件类型是否是图片类型

*typeImages可以设置图片类型

*@createDateOct10,201012:19:18PM

*@paramfileName验证文件的名称

*@return是否合法

*/

publicstaticbooleanvalidTypeByName4Images(StringfileName){

returnvalidTypeByName(fileName,typeImages);

}

/**

*<b>function:</b>验证当前文件名称、文件类型是否是非图片类型(常用办公文件类型)

*typeOthers可以设置文件类型

*@createDateOct10,201012:21:22PM

*@paramfileName验证文件的名称

*@return是否合法

*/

publicstaticbooleanvalidTypeByName4Others(StringfileName){

returnvalidTypeByName(fileName,typeOthers);

}

文件删除操作,对重名的文件可以删除或是替换

/**

*<b>function:</b>传递一个路径和文件名称,删除该文件

*@createDateOct10,201010:47:57AM

*@paramfileName文件名称

*@parampath路径

*@return是否删除成功

*/

publicstaticbooleanremoveFile(StringfileName,Stringpath){

booleanflag=false;

if(isFileExist(fileName,path)){

Filefile=newFile(getDoPath(path)+fileName);

flag =file.delete();

}

returnflag;

}

/**

*<b>function:</b>删除文件

*@createDateOct10,201010:49:54AM

*@paramfile要删除的文件

*@return是否删除成功

*/

publicstaticbooleanremoveFile(Filefile){

booleanflag=false;

if(file!=null&&file.exists()){

flag =file.delete();

}

returnflag;

}




获得文件类型、后缀、名称等操作

/**

*<b>function:</b>传入一个文件名,得到这个文件名称的后缀

*@createDateOct9,201011:30:46PM

*@paramfileName文件名

*@return后缀名

*/

publicstaticStringgetSuffix(StringfileName){

intindex=fileName.lastIndexOf(".");

if(index!=-1){

Stringsuffix=fileName.substring(index);//后缀

returnsuffix;

}else{

returnnull;

}

}

/**

*<b>function:</b>和文件后缀一样,不同的是没有.

*@createDateOct10,20102:42:43PM

*@paramfileName文件名称

*@return

*/

publicstaticStringgetType(StringfileName){

intindex=fileName.lastIndexOf(".");

if(index!=-1){

Stringsuffix=fileName.substring(index+1);//后缀

returnsuffix;

}else{

returnnull;

}

}

/**

*<b>function:</b>传递一个文件名称和一个新名称,组合成一个新的带后缀文件名

*当传递的文件名没有后缀,会添加默认的后缀

*@createDateOct9,201010:53:06PM

*@paramfileName文件名称

*@paramnewName新文件名称

*@paramnullSuffix为没有后缀的文件所添加的后缀;eg:txt

*@returnString文件名称

*/

publicstaticStringgetNewFileName(StringfileName,StringnewName,StringnullSuffix){

Stringsuffix=getSuffix(fileName);

if(suffix!=null){

newName +=suffix;

}else{

newName=newName.concat(".").concat(nullSuffix);

}

returnnewName;

}

/**

*<b>function:</b>利用uuid产生一个随机的name

*@createDateOct9,201010:45:27PM

*@paramfileName带后缀的文件名称

*@returnString随机生成的name

*/

publicstaticStringgetRandomName(StringfileName){

StringrandomName=UUID.randomUUID().toString();

returngetNewFileName(fileName,randomName,"txt");

}

/**

*<b>function:</b>用当前日期、时间和1000以内的随机数组合成的文件名称

*@createDateOct9,201011:01:47PM

*@paramfileName文件名称

*@return新文件名称

*/

publicstaticStringgetNumberName(StringfileName){

SimpleDateFormatformat=newSimpleDateFormat("yyMMddhhmmss");

intrand=newRandom().nextInt(1000);

StringnumberName=format.format(newDate())+rand;

returngetNewFileName(fileName,numberName,"txt");

}

/**

*<b>function:</b>判断该文件是否存在

*@createDateOct10,201012:00:44AM

*@paramfileName文件名称

*@parampath目录

*@return是否存在

*/

publicstaticbooleanisFileExist(StringfileName,Stringpath){

Filefile=newFile(getDoPath(path)+fileName);

returnfile.exists();

}

/**

*<b>function:</b>返回可用的文件名

*@createDateOct10,20101:02:45AM

*@paramfileName文件名

*@parampath路径

*@return可用文件名

*/

publicstaticStringgetBracketFileName(StringfileName,Stringpath){

returngetBracketFileName(fileName,fileName,path,1);

}

/**

*<b>function:</b>递归处理文件名称,直到名称不重复(对文件名、目录文件夹都可用)

*eg:a.txt-->a(1).txt<br/>

*文件夹upload-->文件夹upload(1)

*@createDateOct10,201012:56:27AM

*@paramfileName文件名称

*@parampath文件路径

*@paramnum累加数字,种子

*@return返回没有重复的名称

*/

publicstaticStringgetBracketFileName(StringfileName,StringbracketName,Stringpath,intnum){

booleanexist=isFileExist(bracketName,path);

if(exist){

intindex=fileName.lastIndexOf(".");

Stringsuffix="";

bracketName =fileName;

if(index!=-1){

suffix =fileName.substring(index);

bracketName =fileName.substring(0, index);

}

bracketName+="("+num+")"+suffix;

num++;

bracketName=getBracketFileName(fileName,bracketName,path,num);

}

returnbracketName;

}

/**

*<b>function:</b>处理后的系统文件路径

*@createDateOct10,201012:49:31AM

*@parampath文件路径

*@return返回处理后的路径

*/

publicstaticStringgetDoPath(Stringpath){

path=path.replace("\\","/");

String lastChar= path.substring(path.length() - 1);

if(!"/".equals(lastChar)){

path+="/";

}

returnpath;

}

/**

*<b>function:</b>创建指定的path路径目录

*@createDateOct9,201011:03:49PM

*@parampath目录、路径

*@return是否创建成功

*@throwsException

*/

publicstaticbooleanmkDir(Stringpath)throwsException{

Filefile=null;

try{

file=newFile(path);

if(!file.exists()){

//file.mkdir();创建子目录,如果父目录不存在则不创建

returnfile.mkdirs();

}

}catch(RuntimeExceptione){

throwe;

}finally{

file=null;

}

returnfalse;

}



上面的上传还需要一个上传状态的枚举对象,代码如下:

packagecom.hoo.enums;


/**

*<b>function:</b>文件上传状态

*@fileNameUploadState.java

*@createDate2010-10-11下午12:18:14

*/

publicenumUploadState{

UPLOAD_SUCCSSS(0,"上传文件成功!"),

UPLOAD_FAILURE(1,"上传文件失败!"),

UPLOAD_TYPE_ERROR(2,"上传文件类型错误!"),

UPLOAD_OVERSIZE(3,"上传文件过大!"),

UPLOAD_ZEROSIZE(4,"上传文件为空!"),

UPLOAD_NOTFOUND(5,"上传文件路径错误!");

privateStringstate;

privateintflag;

publicStringgetState(){

returnthis.state;

}

publicintgetFlag(){

returnthis.flag;

}

UploadState(intflag,Stringstate){

this.state=state;

this.flag=flag;

}

}


  1. 下面看看StrutsActionForm代码。

packagecom.hoo.form;


importorg.apache.struts.action.ActionForm;

importorg.apache.struts.upload.FormFile;


@SuppressWarnings("serial")

publicclassUploadFileFormextendsActionForm{

privateFormFileuploadFile;


publicFormFilegetUploadFile(){

returnuploadFile;

}


publicvoidsetUploadFile(FormFileuploadFile){

this.uploadFile=uploadFile;

}

privateStringparam;


publicStringgetParam(){

returnparam;

}


publicvoidsetParam(Stringparam){

this.param=param;

}

}

uploadFile这个属性是和客户端js中的file_post_name:"uploadFile"属性对应,这个一定要注意,param属性是和客户端的post_params:{"param":"uploadParams"}

中的param对应,如果你还有其他参数都会在这里列举。如果你是上传的时候,文件名出现乱码,那么你最好在这里把文件名用encodeURI转码2次。通过post_params传递到服务器端,然后服务器端用URLDecoder转码即可。

  1. 服务器端上传代码,很简单直接调用UploadFormFileUtils工具类完成上传

packagecom.hoo.action;


importstaticcom.hoo.util.UploadFormFileUtils.maxFileSize;

importstaticcom.hoo.util.UploadFormFileUtils.upload;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.struts.action.Action;

importorg.apache.struts.action.ActionForm;

importorg.apache.struts.action.ActionForward;

importorg.apache.struts.action.ActionMapping;

importorg.apache.struts.upload.FormFile;

importcom.hoo.enums.UploadState;

importcom.hoo.form.UploadFileForm;

importcom.hoo.util.UploadFormFileUtils;


/**

*<b>function:</b>struts多文件上传

*@createDateOct10,20105:14:43PM

*@fileUploadAction.java

*@packagecom.hoo.action

*@projectStrutsUpload

*@version1.0

*/

publicclassUploadActionextendsAction{


publicActionForwardexecute(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,

HttpServletResponseresponse)throwsException{

UploadFileFormuForm=(UploadFileForm)form;

Stringpath=request.getSession().getServletContext().getRealPath(UploadFormFileUtils.path);

maxFileSize=1024*1024*20L;

FormFilefile = uForm.getUploadFile();

UploadStatestate=upload(file,file.getFileName(),path);

System.out.println(uForm.getParam());

response.getWriter().print("{success:"+state.getFlag()+",message:'"+state.getState()+"'}");

returnnull;

}

}

注意:这里上传就是一个方法,很普通的方法。也就是上传一个文件,其实SWFupload的上传是利用queue队列,将队列中的文件依次通过flash向服务器端完成上传。而并不是一次上传或是批量上传。

response.getWriter().print("{success:"+state.getFlag()+",message:'"+state.getState()+"'}");

和客户端的handlers.js函数中的uploadSuccess中的serverData中的内容对应的

vardata=eval("("+serverData+")");

if(data.success==0||data.success=="0"){

progress.setStatus("上传完成!");

}else{

progress.setError();

progress.setStatus("上传失败!"+data.message);

}

这里是将服务器端传递过来的json字符用eval转换成js对象,data就是一个js对象

data.success这里的success就是服务器端字符串中success的值,同样message也是服务器端字符串后面的值。

Strtus-config.xml配置

<struts-config>

<data-sources/>

<form-beans>

<form-beanname="uploadForm"type="com.hoo.form.UploadFileForm"/>

</form-beans>

<global-exceptions/>

<global-forwards/>

<action-mappings>

<actionpath="/upload"name="uploadForm"type="com.hoo.action.UploadAction"scope="request"/>

</action-mappings>

<message-resourcesparameter="struts.ApplicationResources"/>

</struts-config>


支持struts1.xSWFUpload多文件无刷新上传就到此结束。其中对主要的几个文件和js文件中要注意到的地方都指出过。且提供源代码参考,这里提供方法的基本上够用,能完成上传、提示、验证等。

下次有时间会提供ExtJS+SWFUpload+Struts2.x的多文件上传,这个界面更加友好、人性化、功能将更加丰富。


我的博客:http://hoojo.cnblogs.com/

http://blog.csdn.net/IBM_hoojo


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics