Struts2文件上传

Struts2提供了文件上传的框架,Struts2默认的文件上传框架是cos,大家也可以根据自己的需要修改Struts2中的文件上传框架,对于文件上传来说,无论使用Struts2中的哪一种框架,上传方式都是比较简单的。下面用一个案例介绍Struts2的文件上传。

该案例比较简单,允许用户进行文件上传,上传成功提示文件上传的主题,上传失败则提示上传失败的提示,当然为了防止恶意上传,我专门做了一个简单的文件过滤,限制文件的格式

  首先看页面的操作

  

上传成功的情况

上传失败的情况

接下来分析源码

  uploadFile.jsp页面

<%@ 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>文件上传</title>
</head>
<body>
    <s:form action="upload" enctype="multipart/form-data">
            <s:textfield name="title">文件标题</s:textfield>
            <s:file name="upload" label="选择文件"></s:file>
            <s:submit value="上传"></s:submit>
    </s:form>
</body>
</html>

上传文件对应的Action

package test.Action;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class fileUploadAction extends ActionSupport {
    private String title;
    private File upload;
    private String uploadContentType;
    private String uploadFileName;
    private String savePath;
    // 设置文件格式
    private String allowType;

    public String getAllowType() {
        return allowType;
    }

    public void setAllowType(String allowType) {
        this.allowType = allowType;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public File getUpload() {
        return upload;
    }

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

    public String getUploadContentType() {
        return uploadContentType;
    }

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

    public String getUploadFileName() {
        return uploadFileName;
    }

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

    public String getSavePath() {
        return ServletActionContext.getServletContext().getRealPath(savePath);
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    @Override
    public String execute() throws Exception {
        // 获取文件内容
        FileInputStream fin = new FileInputStream(getUpload());
        // 定义一个byte数组
        byte[] buffer = new byte[1024];
        // 建立文件输出流,建立文件位置
        FileOutputStream fout = new FileOutputStream(getSavePath() + "\\" + getUploadFileName());
        // 每读完1M的量就往文件里写
        int len = 0;
        while ((len = fin.read(buffer)) > 0) {
            fout.write(buffer, 0, len);
        }
        System.out.println("fileUploadAction [title=" + title + ", upload=" + upload + ", uploadContentType="
                + uploadContentType + ", uploadFileName=" + uploadFileName + ", savePath=" + savePath + "]");
        return SUCCESS;
    }

    public String filterFileType(String[] types) {
        // 获取文件的格式
        String fileType = this.getUploadContentType();
        System.out.println(fileType);
        if (fileType != null) {
            for (String Type : types) {
                if (Type.equals(fileType)) {
                    return null;
                } else
                    return ERROR;
            }

        }

        return ERROR;
    }

    @Override
    public void validate() {
            //接收验证结果
             String Result=this.filterFileType(getAllowType().split(","));
             if(Result!=null)
             {
                 addFieldError("uploadError", "该文件格式 不正确");
             }
    }

}

Struts.xml代码

<?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.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />

    <package name="upload" extends="struts-default">
        <action name="upload" class="test.Action.fileUploadAction">
                <param name="savePath">/WEB-INF/uploadFiles</param>
                <param name="allowType">image/x-png,</param>
                <result>/success.jsp</result>
                <result name="input">/uploadError.jsp</result>
        </action>
    </package>

</struts>

分别对应的成功和失败两个jsp 视图

<%@ 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>结果</title>
</head>
<body>
    上传成功
    文件标题:<s:property value="title" /><br>
    文件为:<s:property value="upload"/>

</body>
</html>
<%@ 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>更新失败</title>
</head>
<body>
    <s:fielderror name="uploadError"></s:fielderror>
</body>
</html>
时间: 2024-08-06 20:00:20

Struts2文件上传的相关文章

struts2 文件上传下载

四.文件的上传(拦截器)和下载(stream结果类型)(需要练一遍) 1.文件上传 必要前提: a.表单method必须是post: b.enctype取值必须是multipart/form-data: c.提供文件选择域. 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib uri="/struts-t

struts2文件上传下载

文件上传 1.struts2中文件上传介绍 struts2文件上传需要使用apache提供的文件上传组件(commons-fileupload.jar和commons-io.jar). struts2文件上传的核心是通过fileupload拦截器实现的. 2.如何实现文件上传 1>.添加commons-fileupload和commons-io包 2>.在jsp页面做如下配置 将form的method属性值设置为post 给form标记添加属性enctype="multipart/f

struts2文件上传突破2M限制

strutsuploadfileactionclass struts配置文件 [html] view plaincopyprint? 1. <action name="FileUpload" class="cn.timefly.strutsTest.FileUploadAction">   2.     <result name="success">/FileUploadResult.jsp</result> 

如何自学Struts2之Struts2文件上传[视频]

如何自学Struts2之Struts2文件上传[视频] 之前写了一篇"打算做一个视频教程探讨如何自学计算机相关的技术",优酷上传不了,只好传到百度云上: http://pan.baidu.com/s/1kTDsa95 由于本次视频没有声音,将会在下节课"Struts2数据库访问"这一节课,一起再讲一下. 注意:不好意思,不知道为什么在这次录制过程中没有声音,很抱歉,本节重点是碰到一个空指针异常,原因是fileUpload这个拦截器要放在其他拦截器之前才没有问题,材料

如何自学Struts2之Struts2文件上传和数据库访问[视频]

如何自学Struts2之Struts2文件上传和数据库访问[视频] 之前写了一篇"打算做一个视频教程探讨如何自学计算机相关的技术",优酷上传不了,只好传到百度云上: http://pan.baidu.com/s/1kTDsa95 由于上次视频没有声音,所以在这节课"Struts2数据库访问"一起再讲一下.

struts2学习(13)struts2文件上传和下载(1)

一.Struts2文件上传: 二.配置文件的大小以及允许上传的文件类型: 三.大文件上传: 如果不配置上传文件的大小,struts2默认允许上传文件最大为2M: 2097152Byte: 例子实现: com.cy.action.FileUploadAction.java: package com.cy.action; import java.io.File; import org.apache.commons.io.FileUtils; import com.opensymphony.xwork

Struts2 文件上传 进度条显示

参考成功博客:http://blog.sina.com.cn/s/blog_bca9d7e80101bkko.html 待测试博客:http://blog.csdn.net/z69183787/article/details/52536255 Struts2 文件上传 进度条显示

Struts2之struts2文件上传详解

一.学习案例:通过在uploadfile.jsp页面填写完表单,提交后跳转到success.jsp页面,然后验证upload包下上传文件是否成功. 二.案例分析:struts2文件上传并不是表面上看的只需简单配置就可以上传文件.实际是分为两步的.1.struts2首先将客户端上传的文件保存到struts.multipart.saveDir键所指定的目录,如果该键所对应的目录不存在,就会保存到javax.servlet.context.tempdir环境变量所指定的目录中.2.Action中所定义

【SSH2(实践篇)】--Struts2文件上传下载实例

上篇文章又一次回顾了Struts2的运行机制,对它的运行步骤做了一步步的解析,这个解析不但再一次理清了Struts2的使用方法,而且对它的映射机制进行了深入的解析,并在最后通过一个实例来介绍了Struts2的一种使用方法,这里将做一个有关文件上传下载的实例. 一.文件上传 Struts2并没有提供文件上传的组件,所以想要实现上传的功能就必须通过第三方组件来实现,在Struts2引用的jar中包含了文件上传的组件,它是通过commons-fileupload.jar和commons-io.jar来

struts2文件上传大小限制问题小结

一:首先看一下程序执行中出现的对应报错信息,如下所示: [WARN ] 2015-03-03 15:31:11 :Unable to parse request org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (78871114) exceeds the configured maximum (52428800) a