struts2实现文件批量上传功能

来源:互联网 发布:加工中心圆弧编程实例 编辑:程序博客网 时间:2024/06/05 05:57

1、--------------------------------------------jsp页面显示部分-------------------------------------------------------------------------

<s:form action="upload" name="upForm" method="post" enctype="multipart/form-data">
  <s:textfield name="title" label="文件标题" /><br/>
  <s:file name="file" label="选择文件1" />
  <s:file name="file" label="选择文件2" />
  <s:file name="file" label="选择文件3" />
  <s:submit value="上传"/>
  </s:form>

2--------------------------------------------action类----------------------------------------------------------------------------------------

public class uplaodAction extends ActionSupport{
private List<File> file;
private List<String> fileFileName;
private List<String> fileContentType;
//这个属性是配置struts.xml文件来注入的
private String savePath;

public void setSavePath(String value){
this.savePath=value;
}
public String getSavePath(){
return ServletActionContext.getServletContext().getRealPath("/WEB-INF/"+savePath);
}
public String execute() throws Exception {
System.out.println("看看路径"+getSavePath());
try{

//循环写入
for(int i=0;i<file.size();i++){
//以服务器的文件保存地址和原文件名建立上传文件输出流
FileOutputStream fos=new FileOutputStream(getSavePath()+"\\"+this.getFileFileName().get(i));
//建立输入流
FileInputStream fis=new FileInputStream(file.get(i));
//建立缓冲区
byte[] buffer=new byte[1024];
int length=0;
//循环从缓冲区读取内容到输入流中
while((length=fis.read(buffer))>0){
fos.write(buffer, 0, length);
}
}



}catch(Exception e){
e.printStackTrace();
}

return SUCCESS;
}

 注:部分属性的getter和setter方法省略

3、-----------------------------------------------------struts.xml文件内容-------------------------------------------------------

//配置该应用使用的编码格式

<constant name="struts.custom.il8n.resources" value="mess" />
<constant name="struts.il8n.encoding" value="utf-8"></constant>


 <action name="upload" class="com.test.action.uplaodAction">
        <param name="savePath">/upload</param>
        <result name="success">success.jsp</result>
        </action> 


-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

注:批量上传和单个文件上传的区别是多了一个for循环


0 0
原创粉丝点击