Struts2手动实现文件上传过滤

本文介绍如何使用Struts2框架实现文件上传功能,并通过输入校验完成对上传文件类型的过滤。具体包括uploadForm.jsp和succ.jsp两个视图页面的设计,配置文件中对上传Action的设置,以及UploadAction类中对文件上传和类型过滤的实现。

一 视图

1 uploadForm.jsp

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>利用输入校验完成文件过滤</title>
    <s:head/>
</head>
<body>
<s:fielderror/>
<s:form action="upload"
    enctype="multipart/form-data">
    <s:textfield name="title" label="文件标题"/>
    <s:file name="upload" label="选择文件"/>
    <s:submit value="上传"/>
</s:form>
</body>
</html>

2 succ.jsp

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>上传成功</title>
</head>
<body>
    上传成功!<br/>
    文件标题:<s:property value=" + title"/><br/>
    文件为:<img src="<s:property value="'uploadFiles/'
        + uploadFileName"/>"/><br/>
</body>
</html>

二 配置文件

<?xml version="1.0" encoding="GBK"?>
<!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.i18n.encoding" value="GBK"/>
    <package name="lee" extends="struts-default">
    <!-- 配置处理文件上传的Action -->
    <action name="upload" class="org.crazyit.app.action.UploadAction">
        <!-- 动态设置Action的属性值 -->
        <param name="savePath">/uploadFiles</param>
        <!-- 设置允许上传的文件类型 -->
        <param name="allowTypes">image/png,image/gif,image/jpeg</param>
        <result name="input">/WEB-INF/content/uploadForm.jsp</result>
        <!-- 配置Struts 2默认的视图页面 -->
        <result>/WEB-INF/content/succ.jsp</result>
    </action>
        <action name="*">
            <result>/WEB-INF/content/{1}.jsp</result>
        </action>
    </package>
</struts>

三 action

package org.crazyit.app.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.io.*;



public class UploadAction extends ActionSupport
{
    // 封装文件标题请求参数的属性
    private String title;
    // 封装上传文件域的属性
    private File upload;
    // 封装上传文件类型的属性
    private String uploadContentType;
    // 封装上传文件名的属性
    private String uploadFileName;
    // 直接在struts.xml文件中配置的属性
    private String savePath;
    // 定义该Action允许上传的文件类型
    private String allowTypes;
    // allowTypes的setter和getter方法
    public String getAllowTypes()
    {
        return allowTypes;
    }
    public void setAllowTypes(String allowTypes)
    {
        this.allowTypes = allowTypes;
    }

    // 接受struts.xml文件配置值的方法
    public void setSavePath(String value)
    {
        this.savePath = value;
    }
    // 获取上传文件的保存位置
    private String getSavePath() throws Exception
    {
        return ServletActionContext.getServletContext()
            .getRealPath(savePath);
    }

    // title的setter和getter方法
    public void setTitle(String title)
    {
        this.title = title;
    }
    public String getTitle()
    {
        return (this.title);
    }

    // upload的setter和getter方法
    public void setUpload(File upload)
    {
        this.upload = upload;
    }
    public File getUpload()
    {
        return (this.upload);
    }

    // uploadContentType的setter和getter方法
    public void setUploadContentType(String uploadContentType)
    {
        this.uploadContentType = uploadContentType;
    }
    public String getUploadContentType()
    {
        return (this.uploadContentType);
    }

    // uploadFileName的setter和getter方法
    public void setUploadFileName(String uploadFileName)
    {
        this.uploadFileName = uploadFileName;
    }
    public String getUploadFileName()
    {
        return (this.uploadFileName);
    }

    @Override
    public String execute() throws Exception
    {
        // 以服务器的文件保存地址和原文件名建立上传文件输出流
        FileOutputStream fos = new FileOutputStream(getSavePath()
            + "\\" + getUploadFileName());
        FileInputStream fis = new FileInputStream(getUpload());
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fis.read(buffer)) > 0)
        {
            fos.write(buffer , 0 , len);
        }
        fos.close();
        return SUCCESS;
    }

    /**
     * 过滤文件类型
     * @param types 系统所有允许上传的文件类型
     * @return 如果上传文件的文件类型允许上传,返回null
     *           否则返回error字符串
     */
    public String filterTypes(String[] types)
    {
        // 获取允许上传的所有文件类型
        String fileType = getUploadContentType();
        for (String type : types)
        {
            if (type.equals(fileType))
            {
                return null;
            }
        }
        return ERROR;
    }

// 执行输入校验
public void validate()
{
    // 将允许上传文件类型的字符串以英文逗号(,)
    // 分解成字符串数组从而判断当前文件类型是否允许上传
    String filterResult = filterTypes(getAllowTypes().split(","));
    // 如果当前文件类型不允许上传
    if (filterResult != null)
    {
        // 添加FieldError
        addFieldError("upload" , "您要上传的文件类型不正确!");
    }
}
}

四 测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值