Struts2文件上传例子

Posted 鲤鱼-CC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Struts2文件上传例子相关的知识,希望对你有一定的参考价值。

一、首先搭建Struts框架

第一步:引入Strusts2所必须的jar包

第二步:创建并配置web.xml文件,在其中配置Struts2的核心过滤器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Upload</display-name>
    <!-- Struts2 的框架的核心过滤器的配置 start!! -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <!-- Struts2 end !!-->
</web-app>

第三步:创建Struts.xml文件

二,编写代码

1.首先编写前台上传的表单界面:设置enctype="multipart/form-data"属性

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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/>
<s:form action="uploadPro" enctype="multipart/form-data">
<s:textfield name="title" label="文件标题"/><br/>
<s:file name="upload" label="选择文件"/>
<s:submit value="上传"/>
</s:form>
</body>
</html>

2.编写Action类来接收前端传过来的数据

package com.cong.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 UploadAction extends ActionSupport {
    
    private static final long serialVersionUID = 1L;
    //封装文件标题请求参数的属性
    private String title;
    //封装上传文件域的属性
    private File upload;
    //封装上传文件类型的属性
    private String uploadContentType;
    //封装上传文件名的属性
    private String uploadFileName;
    //直接在struts.xml文件中配置值的方法
    private String savePath;
    //返回文件保存位置
    public String getSavePath() {
        return ServletActionContext.getServletContext()
                .getRealPath("/"+savePath); //设置上传文件的保存位置
    }
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }
    //相应setter和getter方法
    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;
    }
   
    @Override
    public String execute() throws Exception {
        //文件输入流获取上传的二进制
        FileInputStream fis = new FileInputStream(getUpload());
        //服务器的文件保存地址和源文件名建立上传文件输出流
        FileOutputStream fos = new FileOutputStream(getSavePath()+
                "\\"+getUploadFileName());byte[] buffer = new byte[1024]; //创建一个缓冲字节数组
        int len = 0;
        while ((len = fis.read(buffer)) > 0){  //循环节读取的的字节数据写到服务器文件夹中
            fos.write(buffer, 0, len);
        }
        return SUCCESS;
    }    
}

3、配置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.custom.il8n.resources" value="mess"></constant>
    <!-- 设置应用使用的解码集 -->
    <constant name="struts.il8n.encoding" value="UTF-8"></constant>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="lee" extends="struts-default">

        <action name="uploadPro" class="com.cong.action.UploadAction">
                <!-- 配置fileUpload拦截器 -->
                <interceptor-ref name="fileUpload">
                <!-- 允许上传的文件类型 ,均为图片类型-->
                <param name="allowedTypes">image/jpeg,image/png,image/gif</param>
                <!-- 允许上传的文件大小 -->
                <param name="maximumSize">1024*1024</param>
                  </interceptor-ref>
                <!-- 配置默认拦截器 ,切记!! -->
                 <interceptor-ref name="defaultStack"/>
                <param name="savePath">/images</param> <!--g给savePath属性赋值-->
                <result name="input">index.jsp</result>
                <result>/WEB-INF/content/succ.jsp</result>
        </action>
        
        <action name="*">
            <result>/WEB-INF/content/{1}.jsp</result>
        </action>
    </package>

</struts>

4.编写succ.jsp文件,上传成功后显示结果界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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>
    上传成功<br/>
    文件标题:<s:property value="title"/><br/> <!--显示传过来的字符串数据-->
    文件为:<img src="${pageContext.request.contextPath}/images/<s:property value="+uploadFileName"/>"/><br/> <!--显示上传的图片-->
</body>
</html>

 

以上是关于Struts2文件上传例子的主要内容,如果未能解决你的问题,请参考以下文章

struts2学习笔记--上传单个和批量文件示例

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

struts2的文件上传

struts2实现文件上传和下载

Struts2文件上传(基于表单的文件上传)

Struts2学习—文件上传和下载