struts2实现单个和多个文件的上传

2 篇文章 0 订阅

        struts2本身没有提供解析上传文件内容的功能,但是他使用第三方组件提供对文件上传的支持。struts2的默认的文件上传组件是apache的commons-fileupload组件,该组件性能优异而且支持任意大小的文件上传。commons-fileupload组件从1.1版本开始依赖apache的另一个项目:commons-io,本次使用的是2.0版本。

         struts2提供了一个文件上传拦截器:org.apache.struts2.interceptor.FileUploadInterceptor,他负责调用顶层的文件上传组件解析文件内容,并为action准备与上传文件相关的属性值。处理文件上传请求的action必须提供特殊样式命名的属性,例如需要上传的是image图片,那么action中就应该提供以下三个属性:

  1. image:java.io.File类型,上传文件的File对象;
  2. imageFileName:上传文件的文件名;
  3. imageContentType:上传文件的内容类型(MIME类型);

         这三个属性的值会由FileUploadInterceptor拦截器准备。

        以下就以实例介绍利用该组件实现单个和多个文件的上传和下载。

1、新建web工程Struts2_FileUpload

2、编辑上传文件的Action类,在其类中定义三个变量,分别代表上传文件的对象,上传文件的名称,上传文件的MIME类型,并重写execute()方法,把上传文件保存在WEB-INF/UploadFiles文件夹下。FileUploadAction类代码如下:

package com.struts2.actions;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 文件上传Action类
 * @author 江南渔翁
 */
public class FileUploadAction extends ActionSupport {
    // 代表上传文件的file对象
    private File file;

    // 上传文件名
    private String fileFileName;

    // 上传文件的MIME类型
    private String fileContentType;

    // 上传文件的描述信息
    private String description;

    // 保存上传文件的目录,相对于Web应用程序的根路径,在struts.xml文件中配置
    private String uploadDir;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUploadDir() {
        return uploadDir;
    }

    public void setUploadDir(String uploadDir) {
        this.uploadDir = uploadDir;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    @Override
    public String execute() throws Exception {
        String newFileName = null;
        // 得到当前时间自1990年1月1日0时0分0秒开始流逝的毫秒数,将这个毫秒数作为上传文件的新文件名
        long now = new Date().getTime();
        // 得到保存上传文件的目录的真实路径
        String path = ServletActionContext.getServletContext().getRealPath(uploadDir);
        File dir = new File(path);
        // 如果这个目录不存在,则创建它
        if (!dir.exists()) {
            dir.mkdir();
        }
        int index = fileFileName.lastIndexOf('.');
        // 判断上传文件名是否有扩展名,以时间截取为新的文件名
        if (index != -1) {
            newFileName = now + fileFileName.substring(index);
        } else {
            newFileName = Long.toString(now);
        }

        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        // 读取保存在临时目录下的上传文件,写入到新的文件中
        try {
            FileInputStream fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);

            FileOutputStream fos = new FileOutputStream(new File(dir, newFileName));
            bos = new BufferedOutputStream(fos);

            byte[] buf = new byte[4096];

            int len = -1;
            while ((len = bis.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
        } finally {
            try {
                if (null != bis) {
                    bis.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            try {
                if (null != bos) {
                    bos.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return SUCCESS;
    }
}

3、在项目的src目录下新建struts-config文件夹,在其内新建fileupload.xml文件,配置FileUploadAction类,代码如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!-- 指定拦截器的DTD信息 -->
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
   
<struts>
	<constant name="struts.multipart.maxSize" value="100000000"/>
	<package name="upload" namespace="/upload" extends="fileupload">
		<action name="upload" class="com.struts2.actions.FileUploadAction">
			<interceptor-ref name="fileUpload">
				<param name="maximumSize">10000</param>
				<param name="allowedTypes">
					image/gif,image/jpeg,image/png
				</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack"/>
			<result name="input">/fileupload.jsp</result>
			<result name="success">/success.jsp</result>
			<param name="uploadDir">/WEB-INF/UploadFiles</param>
		</action>
	</package>
</struts>


4、把fileupload.xml文件引入到struts.xml文件中,代码如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!-- 指定拦截器的DTD信息 -->
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
   
<struts>
	<!-- 通过常量配置Struts2所使用的解码集 -->
	<constant name="struts.i18n.encoding" value="gbk" />
	<constant name="struts.devMode" value="true" />
	<include file ="struts-config/fileupload.xml" />
	<package name="fileupload" namespace="/fileupload" extends="struts-default"/>
</struts>

 

5、在src下新建org.apache.struts2包,并在这个包下新建struts-messages.properties文件,修改上传过滤失败后的提示错误信息内容,代码如下:

#改变文件类型不允许的提示信息
struts.messages.error.content.type.not.allowed=您上传的文件类型只能是图片文件!请重新选择!
#改变上传文件太大的提示信息
struts.messages.error.file.too.large=您要上传的文件太大,请重新选择!



6、在WebContent下新建页面fileupload.jsp,代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@taglib prefix="s" uri="/struts-tags"%>

		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>

<head>
<title>文件上传</title>
</head>

<body>
		<h1>上传文件</h1>
		<hr />
		<!-- 使用红色的前景色输出错误信息 -->
		<div style="color:red">
			<s:fielderror/>
		</div>
		<s:form action="upload/upload.action" method="post" enctype="multipart/form-data">
					<s:file name="file" label="请选择上传的文件" />
					<s:textarea name="description" cols="50" rows="10" label="文件描述"></s:textarea>
					<s:submit value="  上   传   " align="center" cssClass="button"/>
		</s:form>
</body>
</html>


7、在同一文件夹下新建success.jsp,用来提示上传成功的信息,代码如下:



 

      

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值