2009年12月16日 星期三

實作Struts2多檔案上傳範例


1.建立多檔案上傳頁面(multiFileUpload.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 'multiFileUpload.jsp' starting page</title>

    <script type="text/javascript">

     function addRow(){

      //插入第一列

   //var x=document.getElementById('fTable').insertRow(0);

   //插入最後一列

   //var x=document.getElementById('fTable').insertRow();

   //抓取表格列數

   var rows = document.getElementById('fTable').rows.length;

   //插入指定的列

   var x = document.getElementById('fTable').insertRow(rows-2);

   var y=x.insertCell(0);

   var z=x.insertCell(1);

   y.innerHTML="檔案名稱:";

   z.innerHTML="<input type=\"file\" name=\"upload\">";

     }

     function delRow(){

      //刪除最後一列

      //var x=document.getElementById('fTable').deleteRow();

   //抓取表格列數

   var rows = document.getElementById('fTable').rows.length;      

      //刪除指定的列

      var x=document.getElementById('fTable').deleteRow(rows-3);

     }

    </script>

  </head>

  

  <body>

   <font color="red"><s:actionerror/></font>

   <font color="red"><s:fielderror/></font>

    <form action="<%=path%>/multiFileUpload" method="post" enctype="multipart/form-data">

     <table id="fTable">

      <tr>

       <td>檔案名稱:</td>

       <td><input type="file" name="upload"></td>

      </tr>

      <tr>

       <td>檔案名稱:</td>

       <td><input type="file" name="upload"></td>

      </tr>

      <tr>

       <td>檔案名稱:</td>

       <td><input type="file" name="upload"></td>

      </tr>        

      <tr>

       <td colspan="2" align="left"><input type="button" value="冊除列" onclick="delRow()">&nbsp;&nbsp;&nbsp;<input type="button" value="新增上傳檔案" onclick="addRow();"></td>

      </tr>           

      <tr>

       <td colspan="2" align="left"><input type="submit" value="上傳..."></td>

      </tr>    

      </table>

    </form>

  </body>

</html>


2.建立上傳成功頁面(multiFileUpload_Success.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 'multiFileUpload_Success.jsp' starting page</title>

  </head>

  

  <body>

 <font color="red">FileUpload ok!!</font>

 <hr>

 <s:iterator value="#request.list" id="f"> 

 FullFileName:<s:property value="#f.fileName"/><br>

 FileContentType:<s:property value="#f.contentType"/><br>

 RealPath(Save):<s:property value="#f.savePath"/><br><br>

 <hr color="blue">

 </s:iterator>

  </body>

</html>


3.建立上傳Action(FileUploadAction.java):
3.1.建立FileInfo class(FileInfo.java):
package com.bean.test;



public class FileInfo {

 private String fileName;

 private String contentType;

 private String savePath;

 public String getFileName() {

  return fileName;

 }

 public void setFileName(String fileName) {

  this.fileName = fileName;

 }

 public String getContentType() {

  return contentType;

 }

 public void setContentType(String contentType) {

  this.contentType = contentType;

 }

 public String getSavePath() {

  return savePath;

 }

 public void setSavePath(String savePath) {

  this.savePath = savePath;

 }

 

}


3.2.建立上傳Action(MultiFileUploadAction.java):
package com.action.test;



import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;



import org.apache.struts2.ServletActionContext;



import com.bean.test.FileInfo;

import com.opensymphony.xwork2.ActionContext;

import com.opensymphony.xwork2.ActionSupport;



public class MultiFileUploadAction extends ActionSupport {

 /**

  * 

  */

 private static final long serialVersionUID = 1L;

 private File[] upload;

 private String[] uploadContentType;

 private String[] uploadFileName;

 private String savePath;

 private String targetDir;

  

 public File[] getUpload() {

  return upload;

 }

 public void setUpload(File[] upload) {

  this.upload = upload;

 }

 public String[] getUploadContentType() {

  return uploadContentType;

 }

 public void setUploadContentType(String[] uploadContentType) {

  this.uploadContentType = uploadContentType;

 }

 public String[] getUploadFileName() {

  return uploadFileName;

 }

 public void setUploadFileName(String[] uploadFileName) {

  this.uploadFileName = uploadFileName;

 }

 public String getSavePath() {

  this.savePath = ServletActionContext.getServletContext().getRealPath(getTargetDir());

  return savePath;

 }

 public void setSavePath(String savePath) {

  this.savePath = savePath;

 }

 public String getTargetDir() {

  return targetDir;

 }

 public void setTargetDir(String targetDir) {

  this.targetDir = targetDir;

 }

 

 @Override

 public String execute() throws Exception {

  return doUpload();

 }



 @SuppressWarnings("unchecked")

 public String doUpload(){

  if(upload==null){

   this.addActionError("請選擇檔案!!");

   return INPUT;

  }

  Map request = (Map)ActionContext.getContext().get("request");

  List list = new ArrayList();  

  for(int i=0;i<this.upload.length;i++){

   String path = this.upload[i].getPath();

   try {

    FileInputStream in = new FileInputStream(path);

    FileOutputStream os = new FileOutputStream(this.getSavePath()+"\\"+this.uploadFileName[i]);

    try {

     byte[] b = new byte[1024];

     int len=0;

     while((len=in.read(b))>0){

      os.write(b,0,len);

     }

     os.close();

     in.close();

    } catch (IOException e) {

     e.printStackTrace();

    }   

   } catch (FileNotFoundException e) {

    e.printStackTrace();

   }

   FileInfo fi = new FileInfo();

   fi.setFileName(this.getUploadFileName()[i]);

   fi.setContentType(this.getUploadContentType()[i]);

   fi.setSavePath(this.getSavePath());

   list.add(fi);

  }

  request.put("list", list);

  return SUCCESS;  

 }

}


4.於struts.xml(src目錄下)加入Struts2 Action:
<action name="multiFileUpload" class="com.action.test.MultiFileUploadAction">

<interceptor-ref name="fileUpload"> 

<!-- 可以上傳之檔案格式 -->

<param name="allowedTypes">

                 image/png,

                 image/gif,

                 image/jpeg,

                 text/plain,

                 text/html,

                 application/octet-stream,

                 application/msword,

                 application/vnd.openxmlformats-officedocument.wordprocessingml.document,

                 application/x-zip-compressed

</param>

<!-- 單一檔案之最大可上傳檔案大小 -->

<param name="maximumSize">4096000</param>

</interceptor-ref> 

<interceptor-ref name="defaultStack" />   

<result>/test/multiFileUpload_Success.jsp</result>

<result name="input">/test/multiFileUpload.jsp</result>

<param name="targetDir">\\upload</param>

</action>


若需限制每次檔案最大可上傳之大小,可加入下面參數於struts.xml內:
<!-- 一次最大上傳之檔案大小 -->

<constant name="struts.multipart.maxSize" value="10240000"></constant>


指定上傳之暫存檔之目錄,可加入下面參數於struts.xml內:
<!-- temp dir -->

<constant name="struts.multipart.saveDir" value="C:\\Program Files (x86)\\Apache Software Foundation\\Tomcat 6.0\\webapps\\Demo\\upload"></constant>


5.測試結果:





看到此畫面,恭喜您實作Struts2多檔案上傳範例成功!

沒有留言:

張貼留言