java_struts2实现文件上传

1.需要导入的架包:commons-fileupload-1.2.1.jar / commons-io-1.3.2.jar

2.为form表单的entctype设置为:multipart/form-data;

例如:

<form name ="frm1" enctype="multipart/form-data" action="${pageContext.request.contextPath}/control/employeex/list_fileUpDown.action" method="post" >
      文件路径:<input type="file" name="uploadImg" />
     <input type="submit" value = "确 定" />
    </form>

3.在Action类中添加以下控件属性:(注。红色的为Struts2的规定固定的)

public class FileUpTest(){

  private File  uploadImg;   //得到上传的文件 

  private String  uploadImgContentType; //得到文件的类型

  private String  uploadImgFileName; //得到上传文件的名称

  //相应的   get  set   ...

  public String fileUpDown(){
      String path = ServletActionContext.getServletContext().getRealPath("/images");
      File saveFile = new File(new File(path),uploadImgFileName);
      if(this.uploadImg!=null){
         try {
            if(!saveFile.getParentFile().exists())
              saveFile.getParentFile().mkdirs();
            FileUtils.copyFile(uploadImg, saveFile);
            this.message="恭喜你,上传成功!";
         } catch (IOException e) {

          //这里就不出来异常了,可以自己去处理
            e.printStackTrace();
         }
       }else{
            this.message="没有找到源文件!";
      }
         return "message";
      }

}

如果上传的是多个文件,只要帮文件字段设置为List或数组都可以,上传文件名和类型也应该为List或数组,他们是对应的。

原文地址:https://www.cnblogs.com/hwj2wj/p/2824679.html