java struts2入门学习实例--使用struts2快速实现多个文件上传

一、错误提示信息配置

昨天说到更改默认错误配置信息,我测试很多遍,一直都不对。下面贴出来,待以后有好方法了再补充吧。

首先新建一个properties文件,这里命名为testupload.properties,内容为:

struts.messages.error.file.too.large=\u6587\u4EF6\u592A\u5927{0} "{1}" "{2}" {3}
struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u7C7B\u578B\u4E0D\u5141\u8BB8! {0} "{1}" "{2}" {3}
struts.messages.error.file.extension.not.allowed=\u4E0D\u5141\u8BB8\u7684\u6269\u5C55\u540D! {0} "{1}" "{2}" {3}

这里将默认提示信息改为中文的。upload.xml中内容如下:

java struts2入门学习实例--使用struts2快速实现多个文件上传
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <!-- 对上传文件总大小进行设置 -->
    <constant name="struts.multipart.maxSize" value="20971520"></constant>
    <!-- 错误信息提示 -->
    <constant name="struts.custom.i18n.resources" value="testupload"/>
    
    <package name="upload" extends="struts-default">
        <action name="UploadAction" class="action.UploadAction" method="uploadMethod">
            <result name="success" type="dispatcher">
                /WEB-INF/upload_success.jsp
            </result>
            <result name="input" type="dispatcher">
                upload.jsp
            </result>
            <!-- 对系统的拦截器进行设置 -->
            <interceptor-ref name="fileUpload">
                <!-- 对单个上传文件的大小进行设置,5M -->
                <param name="maximumSize">5242880</param>
                <!-- 对允许的文件扩展名进行设置,这里以英文逗号隔开 -->
                <param name="allowedExtensions">.txt,.xml</param>
                <!-- 对允许的文件类型进行设置,这里以英文逗号进行隔开 -->
                <param name="allowedTypes">text/plain,text/xml</param>
            </interceptor-ref>
            <!-- 显示引用默认的拦截器 -->
            <interceptor-ref name="defaultStack"></interceptor-ref>
        </action>
    </package>

</struts>
java struts2入门学习实例--使用struts2快速实现多个文件上传

 

二、多个文件上传

只需要更改upload.jsp中的部分内容即可:

java struts2入门学习实例--使用struts2快速实现多个文件上传
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <s:form action="UploadAction" enctype="multipart/form-data" method="POST">
        <s:textfield label="上传用户" name="username"/>
        <s:file label="上传文件" name="upload" />
        <s:file label="上传文件" name="upload" />
         <s:file label="上传文件" name="upload" />
        
        <s:submit value="提交"/>
    </s:form>
</body>
</html>
java struts2入门学习实例--使用struts2快速实现多个文件上传

结果如下所示:

java struts2入门学习实例--使用struts2快速实现多个文件上传

也可以将UploadAction.java中的file改为数组类型的,如下所示:

java struts2入门学习实例--使用struts2快速实现多个文件上传
package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @ClassName: UploadAction
 * @Description: 文件上传
 * @author: amosli
 * @email:amosli@infomorrow.com
 * @date Jan 14, 2014 1:50:28 AM
 */
public class UploadAction extends ActionSupport {
    private static final long serialVersionUID = -8920466592471253212L;
    private String username;// 用户名
    private String[] uploadContentType;// 上传文件的类型,(Fileupload拦截器传入的参数)
    private File[] upload;// 上传的文件,(Fileupload拦截器传入的参数)
    private String[] uploadFileName;// 上传文件的真实文件名,(Fileupload拦截器传入的参数)

    public void setUsername(String username) {
        this.username = username;
    }

    public String[] getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String[] uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public File[] getUpload() {
        return upload;
    }

    public void setUpload(File[] upload) {
        this.upload = upload;
    }

    public String[] getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String[] uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUsername() {
        return username;
    }

    public String uploadMethod() throws Exception {
        ServletContext context = ServletActionContext.getServletContext();
        String real_path = context.getRealPath("/WEB-INF/upload/");
        for (int i = 0; i < upload.length; i++) {
            InputStream inputStream = new FileInputStream(upload[i]);
            OutputStream outputStream = new FileOutputStream(real_path + "/" + uploadFileName);
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            // 关闭流
            inputStream.close();
            outputStream.close();
            // 删除tmp文件,最好是用tyrcatch finally进行删除
            // upload[i].delete();
        }

        return SUCCESS;
    }

}
View Code

这里没有立马删除是想做个演示,查看一下缓存文件空间生成了几个。

首先,将项目打包,生成war包,这里我用的是mvn package打的包。

其次,将tomcat启动,将成生的war包拷到webapp目录下。

最后,在浏览器演示多个文件上传。

演示结果如下图所示:

1、打开浏览器,上传a.txt,b.txt,c.txt三个文件

java struts2入门学习实例--使用struts2快速实现多个文件上传

2、点击提交后,跳转到成功提示页面 

java struts2入门学习实例--使用struts2快速实现多个文件上传

 

3.查看相对应的文件目录,这里没有删除缓存,所以可以看到三个缓存文件

java struts2入门学习实例--使用struts2快速实现多个文件上传

 

 

 

 三、指定文件上传的路径

 如何通过配置文件,手动指定文件的上传目录?

首先,在upload.xml中action标签中指定参数名为uploadPath,赋值为/home/amosli/develop/struts2_learn/

<action name="UploadAction" class="action.UploadAction" method="uploadMethod">
            <param name="uploadPath">/home/amosli/develop/struts2_learn/</param>
.................

全部的upload.xml文件为:

java struts2入门学习实例--使用struts2快速实现多个文件上传
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <!-- 对上传文件总大小进行设置 -->
    <constant name="struts.multipart.maxSize" value="20971520"></constant>
    <!-- 错误信息提示 -->
    <constant name="struts.custom.i18n.resources" value="testupload" />

    <package name="upload" extends="struts-default">
        <action name="UploadAction" class="action.UploadAction" method="uploadMethod">
            <param name="uploadPath">/home/amosli/develop/struts2_learn/</param>
            <result name="success" type="dispatcher">
                /WEB-INF/upload_success.jsp
            </result>
            <result name="input" type="dispatcher">
                upload.jsp
            </result>
            <!-- 对系统的拦截器进行设置 -->
            <interceptor-ref name="fileUpload">
                <!-- 对单个上传文件的大小进行设置,5M -->
                <param name="maximumSize">5242880</param>
                <!-- 对允许的文件扩展名进行设置,这里以英文逗号隔开 -->
                <param name="allowedExtensions">.txt,.xml</param>
                <!-- 对允许的文件类型进行设置,这里以英文逗号进行隔开 -->
                <param name="allowedTypes">text/plain,text/xml</param>
            </interceptor-ref>
            <!-- 显示引用默认的拦截器 -->
            <interceptor-ref name="defaultStack"></interceptor-ref>
        </action>
    </package>
</struts>
View Code

其次,在UploadAction.java中新建一个变量uploadPath,为其设置set方法。同时在uploadMethod方法中将目标文件夹改为uploadPath.

即,UploadAction.java为:

java struts2入门学习实例--使用struts2快速实现多个文件上传
package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @ClassName: UploadAction
 * @Description: 文件上传
 * @author: amosli
 * @email:amosli@infomorrow.com
 * @date Jan 14, 2014 1:50:28 AM
 */
public class UploadAction extends ActionSupport {
    private static final long serialVersionUID = -8920466592471253212L;
    private String username;// 用户名
    private String[] uploadContentType;// 上传文件的类型,(Fileupload拦截器传入的参数)
    private File[] upload;// 上传的文件,(Fileupload拦截器传入的参数)
    private String[] uploadFileName;// 上传文件的真实文件名,(Fileupload拦截器传入的参数)
    private String uploadPath;
    
    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String[] getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String[] uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public File[] getUpload() {
        return upload;
    }

    public void setUpload(File[] upload) {
        this.upload = upload;
    }

    public String[] getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String[] uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUsername() {
        return username;
    }

    public String uploadMethod() throws Exception {
//        ServletContext context = ServletActionContext.getServletContext();
//        String real_path = context.getRealPath("/WEB-INF/upload/");
        for (int i = 0; i < upload.length; i++) {
            InputStream inputStream = new FileInputStream(upload[i]);
            OutputStream outputStream = new FileOutputStream(uploadPath + "/" + uploadFileName[i]);
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            // 关闭流
            inputStream.close();
            outputStream.close();
            // 删除tmp文件,最好是用tyrcatch finally进行删除
            // upload[i].delete();
        }

        return SUCCESS;
    }

}
View Code

最后,运行效果如下:

java struts2入门学习实例--使用struts2快速实现多个文件上传

java struts2入门学习实例--使用struts2快速实现多个文件上传

 

java struts2入门学习实例--使用struts2快速实现多个文件上传

 

 

本文源码:https://github.com/amosli/strut2_learn 

java struts2入门学习实例--使用struts2快速实现多个文件上传

上一篇:验证码识别笔记(三)——Qunar


下一篇:C#高编 - 核心C#