struts2实现文件上传

项目中用到struts2实现文件上传,记录下来,方便以后查看。
struts2默认采用Jakarta的Common-FileUpload框架来实现文件的上传。

1、在web应用中加入相应的jar文件:commons-fileupload-1.2.jar和commons-io-1.3.1.jar。该框架对原上传框架进行了封装,简化了文件上传的代码实现,取消了不同上传框架之间的编程差异。

2、编写jsp页面。修改页面中<form>元素的enctype属性,enctype属性表明数据提交的格式。该属性标识将数据发送到服务器时浏览器使用的编码格式。:

1)、multipart/form-data:表单中的数据被编码为一条消息,页面上的每个控件对应消息的一部分。

2)、application/x-www-form-urlencoded:表单中的数据被编码为名称/值对的形式。是默认的编码格式。

当action为get时,浏览器用x-www-form-urlencoded的编码方式把form数据转换为一个字串 (name1=value1&name2=value2……),然后把这个字串追加到url后面,用?分割,加载这个新的url。

当aciton为post时,浏览器把form数据封装到http boby中,然后发送到服务器。如果没有type="file"的控件,用默认的application/x-www-form-urlencoded,否则用multipart/form-data。浏览器会把整个表单以控件为单位进行分割,并为每个部分加上相关信息(Content-Disposition[form-data或者file]、ContentType[默认为text/plain]、name【控件name】等信息)及分割符。

3) 、text/plain:表单数据以纯文本形式进行编码,其中不含任何控制或格式字符。

3、编写处理上传请求的action。在编写action前,应导入struts2的相应jia包。(xwork-2.0.1.jar、struts2-core-2.0.6.jar、ognl-2.6.11.jar、freemarker-2.3.8.jar、 commons-logging-1.1.jar)

4、编写配置文件。在struts.xml中进行如下信息的配置:

1)、配置处理上传请求的action

2)、配置<constantname="struts.custom.i18n.resources" value="messages"></constant>常量指定资源文件,资源文件可在myEclipse中创建,或通过native2ascii命令进行转换。前者创建的文件不需要转换,自动为utf-8格式。

3)、配置文件上传的拦截器

在struts.properties中配置加载资源文件的信息。

在web.xml中配置过滤器。

具体代码如下:

jsp页面【fileUpload.jsp】:

<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<%@ page pageEncoding="UTF-8"%>
<%@ 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>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>
<form method="post" action="FileUpload.do" enctype="multipart/form-data">
文件:
<input type="file" name="uploadFile" size="50"/><br/>
<input type="submit" value="上传" />

<s:fielderror />
</form>
</body>
</html>
【success.jsp】

<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<%@ page pageEncoding="UTF-8"%>
<%@ 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>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>
<form method="post" action="FileUpload.do" enctype="multipart/form-data">
文件:
<input type="file" name="uploadFile" size="50"/><br/>
<input type="submit" value="上传" />

<s:fielderror />
</form>
</body>
</html>

action代码【FileUploadAction.java】:

package com.mls.fileUpload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class FileUploadAction extends ActionSupport
{
private static final int BUFFER_SIZE = 16*1024;

private File uploadFile; //上传的文件域对象

private String uploadFileFileName; //上传的文件名称

private String uploadFileContentType; //上传的文件类型

private String savePath; //上传文件的保存路径


public File getUploadFile()
{

return uploadFile;
}

public void setUploadFile(File uploadFile)
{

this.uploadFile = uploadFile;
}

public String getUploadFileFileName()
{

return uploadFileFileName;
}



public void setUploadFileFileName(String uploadFileFileName)
{

this.uploadFileFileName = uploadFileFileName;
}



public String getUploadFileContentType()
{

return uploadFileContentType;
}



public void setUploadFileContentType(String uploadFileContentType)
{

this.uploadFileContentType = uploadFileContentType;
}


public String getSavePath()
{

return savePath;
}


public void setSavePath(String savePath)
{

this.savePath = savePath;
}

@Override
public String execute() throws Exception
{
String path = ServletActionContext.getServletContext().getRealPath(this.getSavePath())+"/"+this.getUploadFileFileName();

File dstPath = new File(path);
copy(uploadFile,dstPath);

return SUCCESS;
}

/**
* 将上传的文件复制到目标文件
* @param src
* @param dst
*/
private static void copy(File src,File dst)
{
InputStream in= null;
OutputStream out = null;

try
{
in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);

byte[] buffer = new byte[BUFFER_SIZE];

while((in.read(buffer)) > 0)
{
out.write(buffer,0,BUFFER_SIZE);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(null != in)
{
in.close();
}
if(null != out)
{
out.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
配置文件:

【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.custom.i18n.resources" value="messages"></constant>
<constant name="struts.action.extension" value="do" />

<package name="fileUploadTest" namespace="/"
extends="struts-default">
<action name="FileUpload"
class="com.mls.fileUpload.FileUploadAction">

<interceptor-ref name="fileUpload">
<!-- 配置允许上传的文件类型,多个用英文的","分隔 -->
<param name="allowedTypes">
image/gif,image/png
</param>

<!-- 配置允许上传的文件大小,单位字节 -->
<param name="maximumSize">102400</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />

<param name="savePath">upload</param>
<result>success.jsp</result>
<result name="input">fileUpload.jsp</result>
</action>
</package>
</struts>
【struts.properties】

#Created by JInto - www.guh-software.de
#Sun Jul 29 15:21:44 CST 2010
struts.custom.i18n.resources=messages

struts.devMode=false
struts.enable.DynamicMethodInvocation=true
struts.i18n.reload=true
struts.ui.theme=simple

struts.locale=zh_CN
struts.i18n.encoding=UTF-8

struts.serve.static.browserCache=false
struts.url.includeParams=none

【web.xml】

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<filter>
<filter-name>struts2-cleanup</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>



<welcome-file-list>
<welcome-file>fileUpload.jsp</welcome-file>
</welcome-file-list>
</web-app>

下图为myEclipse中工程目录结构:




资源文件内容:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值