原文地址:http://blog.csdn.net/java_cxrs/article/details/6004144css
描述:html
經過struts2實現多圖片上傳。java
我使用的版本是2.2.1,使用的包有以下幾個:apache
具體實現:瀏覽器
1.建立上傳圖片的頁面tomcat
fileUpload.jsp jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% 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 'fileUpLoad.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" mce_href="styles.css"> --> </head> <body> <center> <s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data" > <s:fielderror /> <s:file name ="myFile" label ="Image File1"/> <s:file name ="myFile" label ="Image File2"/> <s:file name ="myFile" label ="Image File3"/> <s:textfield name ="caption" label ="Caption" /> <s:submit/> </s:form> </center> </body> </html>
在FileUpload.jsp中,先將表單的提交方式設爲POST,而後將enctype設爲multipart/form-data,這並無什麼特別之處。接下來,<s:file/>標誌將文件上傳控件綁定到Action的myFile屬性,由於要上傳多張圖片咱們就暫且添加三個fileide
注意這三個file的name屬性要相同。ui
2.建立處理圖片上傳的actionthis
FileUploadAction.java
package com.ywjava.action; 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 java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class FileUploadAction extends ActionSupport { private static final long serialVersionUID = 572146812454l; private static final int BUFFER_SIZE = 16 * 1024; private List<File> myFile = new ArrayList<File>(); private List<String> contentType = new ArrayList<String>(); private List<String> fileName = new ArrayList<String>(); //文件名 private List<String> imageFileName = new ArrayList<String>(); private String caption; private static void copy(File src, File dst) { try { 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); } } finally { if (null != in) { in.close(); } if (null != out) { out.close(); } } } catch (Exception e) { e.printStackTrace(); } } private static String getExtention(String fileName) { int pos = fileName.lastIndexOf("."); return fileName.substring(pos); } @Override public String execute() { if (myFile == null) return INPUT; for (int i = 0; i < myFile.size(); i++) { imageFileName.add(new Date().getTime()+ getExtention(this.getMyFileFileName().get(i))) ; File imageFile = new File(ServletActionContext.getServletContext() //獲得圖片保存的位置(根據root來獲得圖片保存的路徑在tomcat下的該工程裏) .getRealPath("UploadImages") + "/" + imageFileName); copy(myFile.get(i), imageFile); //把圖片寫入到上面設置的路徑裏 } return SUCCESS; } public List<File> getMyFile() { return myFile; } public void setMyFile(List<File> myFile) { this.myFile = myFile; } public List<String> getContentType() { return contentType; } public void setContentType(List<String> contentType) { this.contentType = contentType; } public List<String> getMyFileFileName() { return fileName; } public void setMyFileFileName(List<String> fileName) { this.fileName = fileName; } public List<String> getImageFileName() { return imageFileName; } public void setImageFileName(List<String> imageFileName) { this.imageFileName = imageFileName; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public static int getBufferSize() { return BUFFER_SIZE; } }
在FileUploadAction中我分別寫了setMyFileContentType、setMyFileFileName、setMyFile和setCaption四個Setter方法,
後二者很容易明白,分別對應FileUpload.jsp中的<s:file/>和<s:textfield/>標誌。可是前二者並無顯式地與任何的頁面標誌綁定,
那麼它們的值又是從何而來的呢?其實,<s:file/>標誌不單單是綁定到myFile,
還有myFileContentType(上傳文件的MIME類型)和myFileFileName(上傳文件的文件名,該文件名不包括文件的路徑)。
所以,<s:file name="xxx" />對應Action類裏面的xxx、xxxContentType和xxxFileName三個屬性。
FileUploadAction做用是將瀏覽器上傳的文件拷貝到WEB應用程序的
UploadImages文件夾下,新文件的名稱是由系統時間與上傳文件的後綴組成,
該名稱將被賦給imageFileName屬性,以便上傳成功的跳轉頁面使用。
3.建立顯示圖片的頁面
showUpload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% 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>Show Image</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" mce_href="styles.css"> --> </head> <body> <s:iterator value="imageFileName" status="length"> <div style="padding: 3px; border: solid 1px #cccccc; text-align: center"> <img src='UploadImages/<s:property value ="imageFileName" /> ' /> <br /> <s:property value="caption" /> </div> </s:iterator> <s:property value ="caption" /> </body> </html>
4.Action配置文件
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.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="false" /> <!-- 指定國際化資源文件的baseName爲messageResource --> <constant name="struts.custom.i18n.resources" value="messageResource" /> <!-- 設置該應用使用的解碼集 --> <constant name="struts.i18n.encoding" value="utf-8" /> <!-- 上傳的所有圖片的最大限制--> <constant name="struts.multipart.maxSize" value="1024102400" /> <!-- 臨時存放文件的路徑 --> <constant name="struts.multipart.saveDir" value="d:/test" /> <package name="index" namespace="/" extends="struts-default"> <action name="index" class="com.ywjava.action.IndexAction"> <result> /WEB-INF/page/fileUpLoad.jsp </result> </action> <action name="fileUpload" class="com.ywjava.action.FileUploadAction"> <!-- 限制圖片的格式和圖片的大小 --> <interceptor-ref name="fileUpload"> <param name="allowedTypes"> image/bmp,image/png,image/gif,image/jpeg,image/pjpeg </param> </interceptor-ref> <!-- 默認的攔截器,必需要寫 --> <interceptor-ref name="defaultStack" /> <result name="input"> /WEB-INF/page/fileUpLoad.jsp</result> <result name="success">/WEB-INF/page/showUpload.jsp</result> </action> </package> <!-- <constant name="struts.multipart.saveDir" value="d:/test"></constant> --> <!-- Add packages here --> </struts>
Action配置文件裏所作的配置都有註釋,不明白的地方看下注釋
另外由於作了國際化處理因此須要一個國際化配置的文件
放在src目錄下
5.國際化配置文件
messageResource_zh_CN.properties(只配置了中文的)
struts.messages.error.content.type.not.allowed=/u4E0A/u4F20/u7C7B/u578B/u9519/u8BEF
struts.messages.error.file.too.large=/u4E0A/u4F20/u6587/u4EF6/u592A/u5927
總結:struts2上傳圖片利用了fileUpload攔截器而變的簡單,主要是在action中作相應處理獲取文件的相應信息。