一、创建上传文件的页面,代码如下所示
1、Struts2也可以很方便地实现多文件上传。 在输入表单域增加多个文件域:multifileupload.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"%> 2 <%@ taglib uri="/struts-tags" prefix="s" %> 3 <html> 4 <head> 5 <title>多文件上传</title> 6 </head> 7 <body> 8 <font color="red"><s:fielderror/></font> 9 <form action="multiFileUpload.action" method="POST" enctype="multipart/form-data"> 10 文件标题:<input type="text" name="title" size="50" value="${param.title }"/><br/> 11 <!-- 设置二个文件域,名字相同 --> 12 选择第一个文件:<input type="file" name="upload" size="50"/><br/> 13 选择第二个文件:<input type="file" name="upload" size="50"/><br/> 14 <input type="submit" value=" 上传 "/> 15 </form> 16 </body> 17 </html>
2、在Action类中用数组来封装该多个文件域:MultiFileUploadAction.java
1 package org.qiujy.web.struts2; 2 import java.io.BufferedInputStream; 3 import java.io.BufferedOutputStream; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.io.OutputStream; 10 import org.apache.struts2.ServletActionContext; 11 import com.opensymphony.xwork2.ActionSupport; 12 publicclass MultiFileUploadAction extends ActionSupport { 13 privatestaticfinalintBUFFER_SIZE = 16 * 1024; 14 // 文件标题 15 private String title; 16 // 用File数组来封装多个上传文件域对象 17 private File[] upload; 18 // 用String数组来封装多个上传文件名 19 private String[] uploadFileName; 20 // 用String数组来封装多个上传文件类型 21 private String[] uploadContentType; 22 // 保存文件的目录路径(通过依赖注入) 23 private String savePath; 24 //以下为所有属性的getter和setter。省略。。。 25 // 自己封装的一个把源文件对象复制成目标文件对象 26 privatestaticvoid copy(File src, File dst) { 27 InputStream in = null; 28 OutputStream out = null; 29 try { 30 in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); 31 out = new BufferedOutputStream(new FileOutputStream(dst), 32 BUFFER_SIZE); 33 byte[] buffer = newbyte[BUFFER_SIZE]; 34 int len = 0; 35 while ((len = in.read(buffer)) > 0) { 36 out.write(buffer, 0, len); 37 } 38 } catch (Exception e) { 39 e.printStackTrace(); 40 } finally { 41 if (null != in) { 42 try { 43 in.close(); 44 } catch (IOException e) { 45 e.printStackTrace(); 46 } 47 } 48 if (null != out) { 49 try { 50 out.close(); 51 } catch (IOException e) { 52 e.printStackTrace(); 53 } 54 } 55 } 56 } 57 @Override 58 public String execute() throws Exception { 59 File[] srcFiles = this.getUpload(); 60 // 处理每个要上传的文件 61 for (int i = 0; i < srcFiles.length; i++) { 62 // 根据服务器的文件保存地址和原文件名创建目录文件全路径 63 String dstPath = ServletActionContext.getServletContext() 64 .getRealPath(this.getSavePath()) 65 + "\" + this.getUploadFileName()[i]; 66 File dstFile = new File(dstPath); 67 this.copy(srcFiles[i], dstFile); 68 } 69 returnSUCCESS; 70 } 71 }
3、在Struts.xml中配置只需要改变action的名称配置其余基本不需要改变什么