在前面的《Apache Commons FileUpload實現多文件上傳》文章中介紹了http://使用第三方組件ApacheCommons FileUpload來實現多文件的上傳,對比今天用struts實現的多文件上傳,總覺得還是struts用起來更加順手,也更加簡潔方便,不忍自己獨享,所以拿出來跟大家一塊分享一下。如果你讀過前面提到的那篇文章,相信再理解本文將會更加容易,另外提供源碼以方便大家學習(點此下載源碼)。由於本文屬於一片純技術文章,廢話就不多說了,下面看一下struts是如何實現多文件上傳的吧。 1. 首先來看前台。在前台頁面中通過js實現上傳控件的添加和刪除。描述的詳細一些就是點一下“增加一行”按鈕就會增加一個上傳控件,同樣點擊該控件後邊的“刪除”則會將該上傳控件去除。目的在於用js實現添加任意數目的文件的功能。 [html] <span style="font-family:Microsoft YaHei;font-size:14px;"><%@ page language="java" pageEncoding="GB18030"%> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>multiUploadDemo</title> <script type="text/javascript" src="js/myjs.js"> </script> </head> <body bgcolor="#ffffff"> <div id="status"></div> <form method="post" action="upload.do" enctype="multipart/form-data" > <table id="tb"></table> <input type="button" name="AddOnLine" value="增加一行" onclick="additem('tb')"/> <input type="submit" name="btnUpload" value="上傳" onclick="upload()"/> </form> </body> </html> </span> 在前台頁面中引用的js文件中的代碼如下: [javascript] <span style="font-family:Microsoft YaHei;font-size:14px;"> var num = 0; function upload(){ document.getElementById("status").innerHTML = "文件上傳中..."; } function additem(id) { var row,cell,str; row = eval("document.all["+'"'+id+'"'+"]").insertRow(); if(row != null ) { cell = row.insertCell(); str="<input type="+'"'+"file"+'"'+" name=uploadFile["+ num +"].file><input type="+'"'+"button"+'"'+" value="+'"'+"刪除"+'"'+" onclick='deleteitem(this,"+'"'+"tb"+'"'+");'>" cell.innerHTML=str; } num++; } function deleteitem(obj,id) { var rowNum,curRow; curRow = obj.parentNode.parentNode; rowNum = eval("document.all."+id).rows.length - 1; eval("document.all["+'"'+id+'"'+"]").deleteRow(curRow.rowIndex); } function callback(msg) { document.getElementById("status").innerHTML = "文件上傳完成...<br>" + msg; }</span> 2. 前台頁面在實現了動態添加上傳控件的功能後,真正用來上傳文件的後台代碼就要隆重登場了,後台代碼中新建三個類,他們分別為UploadActionForm.java,UploadFile.java以及UploadTestAction.java。 UploadActionForm.java類代碼如下: [java] <span style="font-family:Microsoft YaHei;font-size:14px;">package myupload; import java.util.ArrayList; import java.util.List; import org.apache.struts.action.ActionForm; import org.apache.struts.upload.FormFile; public class UploadActionForm extends ActionForm { private List myFiles; public UploadActionForm() { myFiles = new ArrayList(); } public List getMyFiles() { return myFiles; } // 注意這個方法的定義 不加中間的循環是會出錯的 public UploadFile getUploadFile(int index) { int size = myFiles.size(); if (index > size - 1) { for (int i = 0; i < index - size + 1; i++) { myFiles.add(new UploadFile()); } } return (UploadFile) myFiles.get(index); } public void setMyFiles(List myFiles) { this.myFiles = myFiles; } } </span> UploadFile.java類代碼如下: [java] <span style="font-family:Microsoft YaHei;font-size:14px;">package myupload; import java.io.Serializable; import org.apache.struts.upload.FormFile; public class UploadFile implements Serializable { private FormFile file; public FormFile getFile() { System.out.println("run in uploadFile.getFile()"); return file; } public void setFile(FormFile file) { this.file = file; } } </span> UploadTestAction.java類代碼如下: [java] <span style="font-family:Microsoft YaHei;font-size:14px;">package myupload; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.upload.FormFile; import antlr.collections.List; public class UploadTestAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { UploadActionForm multiUploadForm = (UploadActionForm) form; ArrayList myFiles = (ArrayList)multiUploadForm.getMyFiles(); String fileStr = ""; System.out.println(myFiles.size()); for (int i = 0; i < myFiles.size(); i++) { UploadFile uploadFile = (UploadFile) myFiles.get(i); FormFile file = uploadFile.getFile(); if (file == null) { System.out.println("file is null"); } else { FileOutputStream fos = new FileOutputStream("H:\\" + file.getFileName()); fos.write(file.getFileData()); fos.flush(); fos.close(); } } return mapping.findForward("success"); } }</span> 最後就是我們的struts-config.xml文件了: [html] <span style="font-family:Microsoft YaHei;font-size:14px;"><?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd"> <struts-config> <form-beans> <form-bean name="uploadForm" type="myupload.UploadActionForm"/> </form-beans> <action-mappings> <action path="/upload" type="myupload.UploadTestAction" name="uploadForm" scope="request" > <forward name="success" path="/upload_success.jsp"/> </action> </action-mappings> <controller maxFileSize="10M"/> </struts-config></span> 該文件中配置了jsp頁面提交後交由哪個Action進行處理的具體信息,以及上傳成功後的頁面跳轉信息。相信通過應用struts你會發現實現多文件上傳會是一件更簡單的事情。