struts2单个文件上传的两种实现方式
通过2种方式模拟单个文件上传,效果如下所示
开发步骤如下:
1、新建一个web工程,导入struts2上传文件所需jar,如下图
目录结构
2、新建action
第一种方式
package com.ljq.action;
import java.io.file;
import org.apache.commons.io.fileutils;
import org.apache.struts2.servletactioncontext;
import com.opensymphony.xwork2.actioncontext;
import com.opensymphony.xwork2.actionsupport;
@suppresswarnings("serial")
public class uploadaction extends actionsupport{
private file image; //上传的文件
private string imagefilename; //文件名称
private string imagecontenttype; //文件类型
public string execute() throws exception {
string realpath = servletactioncontext.getservletcontext().getrealpath("/images");
//d:\apache-tomcat-6.0.18\webapps\struts2_upload\images
system.out.println("realpath: "+realpath);
if (image != null) {
file savefile = new file(new file(realpath), imagefilename);
if (!savefile.getparentfile().exists())
savefile.getparentfile().mkdirs();
fileutils.copyfile(image, savefile);
actioncontext.getcontext().put("message", "文件上传成功");
}
return "success";
}
public file getimage() {
return image;
}
public void setimage(file image) {
this.image = image;
}
public string getimagefilename() {
return imagefilename;
}
public void setimagefilename(string imagefilename) {
this.imagefilename = imagefilename;
}
public string getimagecontenttype() {
return imagecontenttype;
}
public void setimagecontenttype(string imagecontenttype) {
this.imagecontenttype = imagecontenttype;
}
}
第二种方式
package com.ljq.action;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import org.apache.struts2.servletactioncontext;
import com.opensymphony.xwork2.actionsupport;
@suppresswarnings("serial")
public class uploadaction2 extends actionsupport {
// 封装上传文件域的属性
private file image;
// 封装上传文件类型的属性
private string imagecontenttype;
// 封装上传文件名的属性
private string imagefilename;
// 接受依赖注入的属性
private string savepath;
@override
public string execute() {
fileoutputstream fos = null;
fileinputstream fis = null;
try {
// 建立文件输出流
system.out.println(getsavepath());
fos = new fileoutputstream(getsavepath() + "\\" + getimagefilename());
// 建立文件上传流
fis = new fileinputstream(getimage());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
} catch (exception e) {
system.out.println("文件上传失败");
e.printstacktrace();
} finally {
close(fos, fis);
}
return success;
}
/**
* 返回上传文件的保存位置
*
* @return
*/
public string getsavepath() throws exception{
return servletactioncontext.getservletcontext().getrealpath(savepath);
}
public void setsavepath(string savepath) {
this.savepath = savepath;
}
public file getimage() {
return image;
}
public void setimage(file image) {
this.image = image;
}
public string getimagecontenttype() {
return imagecontenttype;
}
public void setimagecontenttype(string imagecontenttype) {
this.imagecontenttype = imagecontenttype;
}
public string getimagefilename() {
return imagefilename;
}
public void setimagefilename(string imagefilename) {
this.imagefilename = imagefilename;
}
private void close(fileoutputstream fos, fileinputstream fis) {
if (fis != null) {
try {
fis.close();
} catch (ioexception e) {
system.out.println("fileinputstream关闭失败");
e.printstacktrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (ioexception e) {
system.out.println("fileoutputstream关闭失败");
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>
<!-- 该属性指定需要struts2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由struts2处理。
如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->
<constant name="struts.action.extension" value="do" />
<!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
<constant name="struts.serve.static.browsercache" value="false" />
<!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
<constant name="struts.devmode" value="true" />
<!-- 默认的视图主题 -->
<constant name="struts.ui.theme" value="simple" />
<!--<constant name="struts.objectfactory" value="spring" />-->
<!--解决乱码 -->
<constant name="struts.i18n.encoding" value="utf-8" />
<!-- 指定允许上传的文件最大字节数。默认值是2097152(2m) -->
<constant name="struts.multipart.maxsize" value="10701096"/>
<!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
<constant name="struts.multipart.savedir " value="d:/tmp" />
<package name="upload" namespace="/upload" extends="struts-default">
<action name="*_upload" class="com.ljq.action.uploadaction" method="{1}">
<result name="success">/web-inf/page/message.jsp</result>
</action>
</package>
<package name="upload2" extends="struts-default">
<action name="upload2" class="com.ljq.action.uploadaction2" method="execute">
<!-- 动态设置savepath的属性值 -->
<param name="savepath">/images</param>
<result name="success">/web-inf/page/message.jsp</result>
<result name="input">/upload/upload.jsp</result>
<interceptor-ref name="fileupload">
<!-- 文件过滤 -->
<param name="allowedtypes">image/bmp,image/png,image/gif,image/jpeg</param>
<!-- 文件大小, 以字节为单位 -->
<param name="maximumsize">1025956</param>
</interceptor-ref>
<!-- 默认拦截器必须放在fileupload之后,否则无效 -->
<interceptor-ref name="defaultstack" />
</action>
</package>
</struts>
上传表单页面
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<title>文件上传</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<!-- ${pagecontext.request.contextpath}/upload/execute_upload.do -->
<!-- ${pagecontext.request.contextpath}/upload2/upload2.do -->
<form action="${pagecontext.request.contextpath}/upload2/upload2.do"
enctype="multipart/form-data" method="post">
文件:<input type="file" name="image">
<input type="submit" value="上传" />
</form>
<br/>
<s:fielderror />
</body>
</html>
显示结果页面
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<title>上传成功</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
上传成功!
<br/><br/>
<!-- ${pagecontext.request.contextpath} tomcat部署路径,
如:d:\apache-tomcat-6.0.18\webapps\struts2_upload\ -->
<img src="${pagecontext.request.contextpath}/<s:property value="'images/'+imagefilename"/>">
<s:debug></s:debug>
</body>
</html>