Struts2 文件上传

本文详细介绍了使用 Struts2 实现文件上传的过程,包括上传表单的 JSP 源代码、Action 类的 Java 源代码、struts.xml 的配置文件、错误消息配置、上传文件限制和处理成功上传的 JSP 源代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Struts2 实现文件上传

1.upload.jsp源代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Simple Upload</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
		function validate() {
			if(uploadForm.upload.value=="") {
				alert("文件不能为空!");
				return false;
			} else {
				uploadForm.submit();
			}
		}
	</script>
  </head>
  
  <body>
    <s:form action="uploadAction" enctype="multipart/form-data" id="uploadForm">
    	<s:textfield name="title" label="文件标题"/><br/>
    	<s:file name="upload" label="选择文件"/><br/>
    	<s:submit value="上传 " onclick="return validate();"></s:submit>
    </s:form>
  </body>
</html>

2.UploadAction.java源代码如下:

package com.xqh.struts.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 String title; // 封装文件标题请求参数的属性
	private File upload; // 封装上传文件域的属性
	private String uploadContentType; // 封装上传文件类型的属性
	private String uploadFileName; // 封装上传文件名的属性
	private String savePath; // 直接在struts.xml文件中配置的属性

	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;
	}

	// tomcat服务器上的虚拟目录
	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath);
	}

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

	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);
		}
		return SUCCESS;
	}
}
注意:
Struts2实现文件上传的编程关键,就是使用了三个属性来封装文件域(upload),其中一个用于封装该文件的文件名(uploadFileName),一个用于封装该文件的文件类型,一个用于封装该文件的文件内容(uploadContentType)。可以认为:如果表单中包含一个name属性为xxx的文件域(本例中为upload),则对应Action需要使用三个属性来封装该文件域的信息:
  • 类型为File的xxx属性封装了该文件域对应的文件内容。(本例为upload)
  • 类型为String的xxxFileName属性封装了该文件域对应的文件的文件名。(本例为uploadFileName)
  • 类型为String的xxxContentType属性封装了该文件域对应的文件的文件类型。(本例为uploadContentType)

3.struts.xml配置文件(配置拦截器实现文件过滤):

<?xml version="1.0" encoding="UTF-8" ?>
<!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.devMode" value="true" />  
    <constant name="struts.i18n.encoding" value="GBK"></constant>
    <constant name="struts.custom.i18n.resources" value="mess"></constant>
    <package name="upload" namespace="/" extends="struts-default">
        <action name="uploadAction" class="com.xqh.struts.action.UploadAction">
        	<!-- 添加fileUpload拦截器,用于限制上传文件的类型(本例为图片类型) -->
        	<interceptor-ref name="fileUpload">
        		<!-- 限制类型为图片类型 -->
        		<param name="allowedTypes">image/png,image/gif,image/jpeg,image/bmp</param>
        		<!-- 限制上传文件的大小  -->
        		<!--  
        		<param name="maximumSize">10000</param>
        		-->
        	</interceptor-ref>
        	<interceptor-ref name="defaultStack"></interceptor-ref>
        	<!-- 动态配置Action的属性值 -->
        	<param name="savePath">/upload</param>
          	<result name="success">/success.jsp</result>
          	<result name="input">/upload.jsp</result>
        </action>
        <!-- 
        <action name="*">
        	<result>/{1}.jsp</result>
        </action>
         -->
    </package>
</struts>

4.mess.properties文件:

struts.messages.error.content.type.not.allowed=您上传的文件类型只能是图片文件!
struts.messages.error.file.too.large=您要上传的文件太大,请重新选择!

5.index.jsp源代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    <jsp:forward page="upload.jsp"></jsp:forward>
  </body>
</html>

6.success.jsp源代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//处理img显示中文文件名问题
String filename = (String)request.getAttribute("uploadFileName");
filename = new String(filename.getBytes("ISO-8859-1"), "GBK");
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Simple Upload</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    	上传成功!<br/>
    	文件标题:<s:property value="title"/><br/>
    	文件为:<img alt="" src="upload/<%=filename %>"width="100" height="100"/><s:property value="uploadFileName"/> <br/>
    	<a href="index.jsp">返回</a>
  </body>
</html>

7.Struts2_Upload程序目录结构:


访问地址 :localhost:8080/Struts2_Upload/

8.程序运行结果截图:

上传成功:

上传非图片类型文件:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值