通过3种方式模拟多个文件上传,效果如下所示
目录结构
新建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 {
servletactioncontext.getrequest().setcharacterencoding("utf-8");
string realpath = servletactioncontext.getservletcontext().getrealpath("/images");
system.out.println(realpath);
if (image != null) {
file savedir=new file(realpath);
if(!savedir.getparentfile().exists())
savedir.getparentfile().mkdirs();
for(int i=0;i<image.length;i++){
file savefile = new file(savedir, imagefilename[i]);
fileutils.copyfile(image[i], savefile);
}
actioncontext.getcontext().put("message", "文件上传成功");
}
return "success";
}
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;
}
}
第二种方式
package com.ljq.action;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import org.apache.struts2.servletactioncontext;
import com.opensymphony.xwork2.actionsupport;
/**
* 使用数组上传多个文件
*
* @author ljq
*
*/
@suppresswarnings("serial")
public class uploadaction2 extends actionsupport{
private file[] image; //上传的文件
private string[] imagefilename; //文件名称
private string[] imagecontenttype; //文件类型
private string savepath;
@override
public string execute() throws exception {
servletactioncontext.getrequest().setcharacterencoding("utf-8");
//取得需要上传的文件数组
file[] files = getimage();
if (files !=null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
//建立上传文件的输出流, getimagefilename()[i]
system.out.println(getsavepath() + "" + getimagefilename()[i]);
fileoutputstream fos = new fileoutputstream(getsavepath() + "" + getimagefilename()[i]);
//建立上传文件的输入流
fileinputstream fis = new fileinputstream(files[i]);
byte[] buffer = new byte[1024];
int len = 0;
while ((len=fis.read(buffer))>0) {
fos.write(buffer, 0, len);
}
fos.close();
fis.close();
}
}
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;
}
/**
* 返回上传文件保存的位置
*
* @return
* @throws exception
*/
public string getsavepath() throws exception {
return servletactioncontext.getservletcontext().getrealpath(savepath);
}
public void setsavepath(string savepath) {
this.savepath = savepath;
}
}
第三种方式
package com.ljq.action;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.util.list;
import org.apache.struts2.servletactioncontext;
import com.opensymphony.xwork2.actionsupport;
/**
* 使用list上传多个文件
*
* @author ljq
*
*/
@suppresswarnings("serial")
public class uploadaction3 extends actionsupport {
private list<file> image; // 上传的文件
private list<string> imagefilename; // 文件名称
private list<string> imagecontenttype; // 文件类型
private string savepath;
@override
public string execute() throws exception {
servletactioncontext.getrequest().setcharacterencoding("utf-8");
// 取得需要上传的文件数组
list<file> files = getimage();
if (files != null && files.size() > 0) {
for (int i = 0; i < files.size(); i++) {
fileoutputstream fos = new fileoutputstream(getsavepath() + "" + getimagefilename().get(i));
fileinputstream fis = new fileinputstream(files.get(i));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
}
}
return success;
}
public list<file> getimage() {
return image;
}
public void setimage(list<file> image) {
this.image = image;
}
public list<string> getimagefilename() {
return imagefilename;
}
public void setimagefilename(list<string> imagefilename) {
this.imagefilename = imagefilename;
}
public list<string> getimagecontenttype() {
return imagecontenttype;
}
public void setimagecontenttype(list<string> imagecontenttype) {
this.imagecontenttype = imagecontenttype;
}
/**
* 返回上传文件保存的位置
*
* @return
* @throws exception
*/
public string getsavepath() throws exception {
return servletactioncontext.getservletcontext().getrealpath(savepath);
}
public void setsavepath(string savepath) {
this.savepath = savepath;
}
}
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" />
<constant name="struts.multipart.maxsize" value="10701096"/>
<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="upload1" namespace="/upload1" extends="struts-default">
<action name="upload1" class="com.ljq.action.uploadaction2" method="execute">
<!-- 要创建/image文件夹,否则会报找不到文件 -->
<param name="savepath">/image</param>
<result name="success">/web-inf/page/message.jsp</result>
</action>
</package>
<package name="upload2" namespace="/upload2" extends="struts-default">
<action name="upload2" class="com.ljq.action.uploadaction3" method="execute">
<!-- 要创建/image文件夹,否则会报找不到文件 -->
<param name="savepath">/image</param>
<result name="success">/web-inf/page/message.jsp</result>
</action>
</package>
</struts>
上传表单页面upload.jsp
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<!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}/upload1/upload1.do -->
<!-- ${pagecontext.request.contextpath}/upload2/upload2.do -->
<!-- -->
<form action="${pagecontext.request.contextpath}/upload2/upload2.do" enctype="multipart/form-data" method="post">
文件1:<input type="file" name="image"><br/>
文件2:<input type="file" name="image"><br/>
文件3:<input type="file" name="image"><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>
显示页面message.jsp
<%@ 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>my jsp 'message.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">
</head>
<body>
上传成功
<br/>
<s:debug></s:debug>
</body>
</html>
单文件上传
过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.18webapps教程struts2_uploadimages
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.18webappsstruts2_upload -->
<img src="${pagecontext.request.contextpath}/<s:property value="'images/'+imagefilename"/>">
<s:debug></s:debug>
</body>
</html>
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索string
, 文件
, new
this
struts2上传图片代码、struts2 文件上传、struts上传文件、struts1上传文件、struts2文件上传下载,以便于您获取更多的相关知识。