通過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;struts.xml配置文件
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;
}
}
<?xml version="1.0" encoding="utf-8" ?>上傳表單頁面upload.jsp
<!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>
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>顯示頁面message.jsp
<!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>
<%@ 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;struts.xml配置文件
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();
}
}
}
}<?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>