struts 文件上传

=================================== 实现单个文件上传 ======================================

步骤1. 导入jar包: commons-fileupload-x.x.x.jar ; commons-io-x.x.x.jar

步骤2: JSP页面
<s:form action="fileup.action" method="post" enctype="multipart/form-data">
<s:file name="upload" lable="选择文件"></s:file><br/>
<s:submit name="submit" value="上传文件"></s:submit>
</s:form>

步骤3: Action页面

package org.zm.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UpLoadAction extends ActionSupport{

private File upload;
private String uploadContentType; //文件类型
private String uploadFileName; //文件名称
private String savePath; //保存路劲
//省略getter; setter

public String getSavePath() {

return ServletActionContext.getServletContext().getRealPath(savePath);
}

public String execute() throws Exception{

byte[] buffer = new byte[1024];

//读取文件
FileInputStream fis = new FileInputStream(upload);
//保存文件,并保存文件的位置
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + this.getUploadFileName());

int length = fis.read(buffer);
while(length > 0){
fos.write(buffer, 0 , length);
length = fis.read(buffer);
}

fis.close();
fos.flush();
fos.close();
return SUCCESS;

}
}

提示: File类型的 xxx 属性名称和JSP上传表单页面 <s:file>的文件名相同。
String类型的xxxFileName属性,该属性由前面File类型的属性名称和FileName组合而成。
String类型的xxxContentType属性同上。

String类型的savePath名称与步骤3中param的名称保存一致

步骤3: Action.xml文件

<!-- 文件上传 -->
<action name="fileup" class="org.zm.test.UpLoadAction">
<param name="savePath">/upload</param>
<result name="success">no.jsp</result>
</action>


===================================== 实现多个文件上传 ==============================

1. JSP页面
多个 <s:file>

2. Action页面
private File[] upload;
private String[] uploadContentType;
.....

public String execute() throws Exception(){
byte[] buffer = new byte[1024];

for(int i = 0; i < upload.length; i++){
......
}

return SUCCESS;
}

posted @ 2015-07-06 13:58  张曼  阅读(179)  评论(0编辑  收藏  举报