struts2实现多文件上传_struts2实现多文件上传的示例代码

更新时间:2021-07-19    来源:php常用代码    手机版     字体:

【www.bbyears.com--php常用代码】

开发环境JDK1.8 eclipse struts2-2.3.31

1.创建web项目

2.导入struts2核心jar包

3.更改web.xml配置文件(只要配置好struts2的Filter就好)

4.创建src/struts.xml文件

 

 代码如下

  "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

  "http://struts.apache.org/dtds/struts-2.0.dtd">

 

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

 

  

    

      

      WEB-INF/images

      /success.jsp

      /error.jsp

      

        

        image/bmp,image/png,image/gif,image/jpeg

        

        1025956

      

      

      

    

  

 

5.创建src/com.ifan.action.FileUpload.Java

 

 代码如下

packagecom.ifan.action;

 

importjava.io.File;

 

importorg.apache.commons.io.FileUtils;

importorg.apache.struts2.ServletActionContext;

 

importcom.opensymphony.xwork2.ActionContext;

importcom.opensymphony.xwork2.ActionSupport;

 

publicclassFileUploadextendsActionSupport{

 

  privateFile[] image;//上传的文件

  privateString[] imageFileName;//文件名称

  privateString[] imageContentType;//文件类型

 

  publicString execute()throwsException {

    ServletActionContext.getRequest().setCharacterEncoding("UTF-8");

    String realpath = ServletActionContext.getServletContext().getRealPath("/images");

    System.out.println(realpath);

    if(image !=null) {

      File savedir=newFile(realpath);

      if(!savedir.getParentFile().exists())

        savedir.getParentFile().mkdirs();

      for(inti=0;i

        File savefile =newFile(savedir, imageFileName[i]);

        FileUtils.copyFile(image[i], savefile);

      }

      ActionContext.getContext().put("message","文件上传成功");

    }

    return"success";

  }

 

  publicFile[] getImage() {

    returnimage;

  }

 

  publicvoidsetImage(File[] image) {

    this.image = image;

  }

 

  publicString[] getImageContentType() {

    returnimageContentType;

  }

 

  publicvoidsetImageContentType(String[] imageContentType) {

    this.imageContentType = imageContentType;

  }

 

  publicString[] getImageFileName() {

    returnimageFileName;

  }

 

  publicvoidsetImageFileName(String[] imageFileName) {

    this.imageFileName = imageFileName;

  }

}

 

6.创建WebContent/index.jsp ,作为上传文件的页面

 

 代码如下

<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%>

<%@ taglib prefix="s"uri="/struts-tags"%>

<%

  String path = request.getContextPath();

  String basePath = request.getScheme() +"://"+ request.getServerName() +":"+ request.getServerPort()

      + path +"/";

%>

 

 

My JSP'hello.jsp'starting page

 

words"content="keyword1,keyword2,keyword3">

 

 

 

 

 

7.创建WebContent/success.jsp 作为文件上传成功跳转的页面,创建WebContent/error.jsp 作为文件上传失败的页面 , 创建WebContent/images文件夹,作为上传文件的存储位置

本文来源:http://www.bbyears.com/jiaocheng/130693.html

热门标签

更多>>

本类排行