文件上传功能在Struts2中得到了很好的封装,主要使用fileUpload上传组件。

1. 单个文件上传

1.1 创建上传单个文件的JSP页面、显示提交结果的JSP页面

uploadTest1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<%@ page isELIgnored="false"%> 
<%@ taglib uri="/struts-tags" prefix="s"%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
    <head> 
    </head> 
    <body> 
        <s:form action="uploadT1" method="post" enctype="multipart/form-data"> 
            <s:file name="uploadFile"></s:file> 
            <br /> 
            <s:submit value="提交"></s:submit> 
        </s:form> 
    </body> 
</html>

注意:代码中加入了enctype="multipart/form-data";而且使用了<s:file/>标签,尤其注意<s:file/>的name属性。

showResult1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<%@ page isELIgnored="false"%> 
<%@ taglib uri="/struts-tags" prefix="s"%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
    <body> 
        您上传的文件名为:<s:property value="uploadFileFileName" />,存放目录:<s:property value="#request.storeDir"/> 
        <br /> 
        <br/> 
        <!--下载上下文路径--> 
        <s:a href="%{#request.get('javax.servlet.forward.context_path')}/upload/%{uploadFileFileName}">点击这里下载</s:a> 
        <br /> 
    </body> 
</html>

1.2 生成Action类

package com.clzhang.struts2.demo12; 
 
import java.io.File; 
import java.io.IOException; 
import org.apache.commons.io.FileUtils; 
import org.apache.struts2.ServletActionContext; 
import com.opensymphony.xwork2.ActionSupport; 
 
public class UploadTest1Action extends ActionSupport { 
    public static final long serialVersionUID = 1; 
 
    private File uploadFile; 
    private String uploadFileFileName; 
 
    public File getUploadFile() { 
        return uploadFile; 
    } 
    public void setUploadFile(File uploadFile) { 
        this.uploadFile = uploadFile; 
    } 
    public String getUploadFileFileName() { 
        return uploadFileFileName; 
    } 
    public void setUploadFileFileName(String uploadFileFileName) { 
        this.uploadFileFileName = uploadFileFileName; 
    } 
 
    public String execute() throws IOException { 
        // 上传物理路径 
        String targetDirectory = ServletActionContext.getServletContext().getRealPath("/upload"); 
        // 生成上传的File对象 
        File target = new File(targetDirectory, uploadFileFileName); 
        // 复制File对象,从而实现上传文件 
        FileUtils.copyFile(uploadFile, target); 
         
        ServletActionContext.getRequest().setAttribute("storeDir", targetDirectory); 
 
        return SUCCESS; 
    } 
}

Action实例中File变量命名规则

  • 数据类型为File的变量uploadFile和JSP页面中的<s:file/>标签的name属性值要一致,这样才可以使用Struts2的拦截器进行属性值的自动封装。
  • Action实例中有uploadFileFileName变量,对应于上传文件的文件名,它的命名规则就是File的变量名后加FileName。

1.3 设置上传文件相关参数(struts.properties)

struts.multipart.maxSize=2048000000 
struts.multipart.saveDir=/upload

通常此文件存放于WEB-INF\classes目录下。

1.4 修改struts.xml文件

        <action name="uploadT1" class="com.clzhang.struts2.demo12.UploadTest1Action"> 
            <result>/struts2/demo12/showResult1.jsp</result> 
        </action>

1.5 测试

打开IE,输入地址:http://127.0.0.1:8080/st/struts2/demo12/uploadTest1.jsp

结果如下

选择任意一个文件提交后,结果如下

一个,显示了服务器物理存储地址;二个,提供了下载链接。

2. 多个文件上传(属性驱动)

Struts2支持多文件批量上传,将上面的代码中的File类型改成File[]即可。

2.1 创建上传多个文件的JSP页面、显示提交结果的JSP页面

uploadTest2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<%@ page isELIgnored="false"%> 
<%@ taglib uri="/struts-tags" prefix="s"%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
    <head> 
    </head> 
    <body> 
        <s:form action="uploadT2" method="post" enctype="multipart/form-data"> 
            username:<s:textfield name="fileUploadTools.username"></s:textfield> 
            <br /> 
            <s:file name="fileUploadTools.uploadFile"></s:file> 
            <br /> 
            <s:file name="fileUploadTools.uploadFile"></s:file> 
            <br /> 
            <s:file name="fileUploadTools.uploadFile"></s:file> 
            <br /> 
            <s:submit value="提交"></s:submit> 
        </s:form> 
    </body> 
</html>

注意:因为是属性驱动,所以表单元素的命名需要以fileUploadTools打头。

showResult2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<%@ page isELIgnored="false"%> 
<%@ taglib uri="/struts-tags" prefix="s"%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
    <body> 
        您上传的文件名列表: 
        <br/> 
        <!--对Action中对象(fileUploadTools)包含的数组(uploadFileFileName)的遍历--> 
        <s:iterator value="fileUploadTools.uploadFileFileName" status="st"> 
            <s:iterator value="fileUploadTools.uploadFileFileName[#st.index]">  
                <s:property /> 
                <br/> 
            </s:iterator> 
        </s:iterator> 
        <br /> 
    </body> 
</html>

2.2 生成Action类及属性驱动类

UploadTest2Action.java

package com.clzhang.struts2.demo12; 
 
import java.io.IOException; 
 
import com.opensymphony.xwork2.ActionSupport; 
 
public class UploadTest2Action extends ActionSupport { 
    public static final long serialVersionUID = 1; 
 
    // 声明封装了File上传的FileUploadTools类的实例 
    // FileUploadTools类也封装了上传的属性及get和set方法 
    private FileUploadTools fileUploadTools = new FileUploadTools(); 
 
    public FileUploadTools getFileUploadTools() { 
        return fileUploadTools; 
    } 
    public void setFileUploadTools(FileUploadTools fileUploadTools) { 
        this.fileUploadTools = fileUploadTools; 
    } 
 
    @Override 
    public String execute() throws IOException { 
        fileUploadTools.beginUpload(); 
         
        return SUCCESS; 
    } 
}

FileUploadTools.java

package com.clzhang.struts2.demo12; 
 
import java.io.File; 
import java.io.IOException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
 
import org.apache.commons.io.FileUtils; 
import org.apache.struts2.ServletActionContext; 
 
public class FileUploadTools { 
    private String username; 
    private File uploadFile[];// 上传的文件是数组类型 
    private String uploadFileFileName[];// 文件名是数组类型 
    private String uploadFileContentType[]; 
 
    public String getUsername() { 
        return username; 
    } 
    public void setUsername(String username) { 
        this.username = username; 
    } 
    // 上传的ContentType文件类型也是数组类型 
    // 必须要加上对ContentType的声明,否则会出现异常 
    public String[] getUploadFileContentType() { 
        return uploadFileContentType; 
    } 
    public void setUploadFileContentType(String[] uploadFileContentType) { 
        this.uploadFileContentType = uploadFileContentType; 
    } 
    public File[] getUploadFile() { 
        return uploadFile; 
    } 
    public void setUploadFile(File[] uploadFile) { 
        this.uploadFile = uploadFile; 
    } 
    public String[] getUploadFileFileName() { 
        return uploadFileFileName; 
    } 
    public void setUploadFileFileName(String[] uploadFileFileName) { 
        this.uploadFileFileName = uploadFileFileName; 
    } 
 
    public String beginUpload() throws IOException { 
        System.out.println("用户名:" + username); 
 
        String targetDirectory = ServletActionContext.getServletContext().getRealPath("/upload"); 
        for (int i = 0; i < uploadFile.length; i++) { 
            File target = new File(targetDirectory, new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss") 
                    .format(new Date()).toString() + System.nanoTime() + uploadFileFileName[i]); 
 
            FileUtils.copyFile(uploadFile[i], target); 
        } 
 
        return "success"; 
    } 
}

2.3  设置上传文件相关参数(struts.properties),同上

2.4 修改struts.xml文件

        <action name="uploadT2" class="com.clzhang.struts2.demo12.UploadTest2Action"> 
            <result>/struts2/demo12/showResult2.jsp</result> 
        </action>

2.5 测试

打开IE,输入地址:http://127.0.0.1:8080/st/struts2/demo12/uploadTest2.jsp

结果如下:

任意选择三个文件后,提交,结果如下:

发布评论

分享到:

IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

struts2:上传多个文件时实现带进度条、进度详细信息的示范详解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。