论坛首页 Java企业应用论坛

Struts2多文件上传

浏览 2176 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-03-19  

第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。

第二步:把form表的enctype设置为:“multipart/form-data“,如下:

 

form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post"> 
 
  <input  type="file" name="uploadImages"> 
 
  <input  type="file" name="uploadImages"> 
 
</form> 

 第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称 

public class HelloWorldAction{ 
 
  private File[] uploadImages;//得到上传的文件 
 
  private String[] uploadImagesContentType;//得到文件的类型 
 
  private String[] uploadImagesFileName;//得到文件的名称 
 
  //这里略省了属性的getter/setter方法 
 
  public String upload() throws Exception{ 
 
String realpath = ServletActionContext.getServletContext().getRealPath("/images"); 
 
File file = new File(realpath); 
 
if(!file.exists()) file.mkdirs(); 
 
for(int i=0 ;i<uploadImages.length; i++){ File uploadImage = uploadImages; 
 
    FileUtils.copyFile(uploadImage, new File(file, uploadImagesFileName)); 
 
} 
 
return "success"; 
 
  }} 
 
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics