2009年12月24日 星期四

實作Ext file upload功能

今天心血來潮,試試Ext是否可以作到資料上傳之功能,沒想到竟然作成功了,再此與大家分享。

開發環境:
IDE:MyEclipse6.6GA
Web Server:Tomcat 6.0.20
Database:MySql 5.1.36
MVC:Struts2.1.8
FrameWork:Spring2.0,Hibernate3.2
Client UI:Ext2.3.0

一、建立檔案上傳表單頁面(fileUploadForm.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 'onReady.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">

 -->

 <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">

 <link rel="stylesheet" type="text/css" href="css/onReady.css">

 <script type="text/javascript" src="extjs/adapter/ext/ext-base.js"></script>

 <script type="text/javascript" src="extjs/ext-all.js"></script>

 <script type="text/javascript" src="extjs/ext-lang-zh_TW.js"></script> 

 <script type="text/javascript">

 <!--

     var index=3;

     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-3);

   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-4);

     }

 

  Ext.onReady(function() {

   /*

   var upload_fp = new Ext.FormPanel({

    renderTo:'loading',

               items:[

                   {xtype:'textfield',inputType:'file',name:'upload',fieldLabel:'File'}

               ]

               ,buttons:[{text:'Upload',handler:function(){

                    upload_fp.getForm().submit({

                           url:'multiFileUpload.action',

                           method:'post'

                     });

               }}]

               ,fileUpload:true

   });

   */

   var fileField = new Ext.form.TextField({

    id:'fl1',

    fieldLabel:'檔案名稱',

    inputType:'file',

    name:'upload'

   }); 

   var fieldId = "fl";

   var fieldIdIndex = 1;

   function addField() {

     fieldIdIndex++;

     fieldId = 'fl' + fieldIdIndex;

     var mf = Ext.getCmp("myForm");

     var fa = new Ext.form.TextField(

      {xtype:'textfield',

       id:fieldId,

       fieldLabel:'檔案名稱',

       inputType:'file',

       name:'upload',

       anchor: '90%'});

     mf.add(fa);

     mf.doLayout();

   }

   function deleteField(){   

    var mf = Ext.getCmp("myForm");

    mf.remove(fieldId);

    fieldIdIndex--;

    fieldId = 'fl' + fieldIdIndex;

    mf.doLayout();

   }

   

   function upLoadFile(){

    uploadForm.getForm().submit({

     success:function(form,action){

      Ext.Msg.alert('結果','上傳成功');

      uploadForm.getForm().reset();

     },

     failure:function(form,action){

      Ext.Msg.alert('結果',action.result.errorMsg);     

     }

    });

   }   

    var uploadForm =  new Ext.form.FormPanel({

       //renderTo:'my_id',

       //title:'檔案上傳',

       id:'myForm',

       url:'multiFileUpload.action',

       method:'post',

       fileUpload:true,

       width:450,

       labelWidth:80,

       items : [fileField],

       buttons : [ {text: '新增上傳檔案',handler:addField },

            {text: '刪除列',handler:deleteField},

             {text: '上傳',handler:upLoadFile} ]

     });

     var win = new Ext.Window({

      title:'檔案上傳',

      width:450,

      height:300,

      items:uploadForm

     });     

     win.show();

  });

 //-->

 </script>

  </head>

  

  <body>

  <!-- 

   <br>

   <table align="center">

   <tr>

    <td>

     <div class="fileUpload">

   <div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>  

      <div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">  

      <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 colspan="2">檔案上傳</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>檔案名稱:</td>

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

         </tr>        

         <tr>

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

         </tr>

         <tr>

          <td colspan="2">&nbsp;</td>

         </tr>          

         <tr>

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

         </tr>    

         </table>

       </form> 

      </div></div></div>  

   <div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>

   </div>

  </td>

 </tr>

 <tr>

  <td>&nbsp;</td>

 </tr>

 <tr>

  <td><div id="my_id"></div></td>

 </tr>

 </table>

  -->

  <div id="loading"></div>

  </body>

</html>

二、建立fileUpload action及File Info bean:
1.File Info bean(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;

 }

 

}


2.fileUpload 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;

 private String jsonString;

 private boolean errorFlag;

  

 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;

 }

 public String getJsonString() {

  return jsonString;

 }

 public void setJsonString(String jsonString) {

  this.jsonString = jsonString;

 }

 

 public String execute() throws Exception {

  return doUpload();

 }



 public String doUpload(){

  if(errorFlag){

   return SUCCESS;

  }

  if(upload==null){

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

   this.jsonString = "{\"failure\":\"true\",\"errorMsg\":\"請選擇檔案!!\"}";

   return SUCCESS;

  }

  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);

  this.jsonString = "{\"success\":\"true\"}";

  return SUCCESS;  

 }

 

 public void validate() {

  //check upload file field error information(Content-Type not allow,File to large...)

  Map fieldErrors = this.getFieldErrors();

  for(int i=0;i<fieldErrors.size();i++){

   Object[] o = fieldErrors.values().toArray();

   for(int j=0;j<o.length;j++){

    String msg = o[j].toString().substring(1, o[j].toString().length()-1);

    msg = msg.replaceAll(":","").replaceAll("\"", "");

    //System.out.println(msg);

    this.jsonString = "{\"failure\":\"true\",\"errorMsg\":\""+msg+"\"}";

    this.clearFieldErrors();

    errorFlag=true;

    try {

     execute();

    } catch (Exception e) {

     e.printStackTrace();

    }

   }

  }

  

  //check upload file action error information(the request was rejected because its size (13711848) exceeds the configured maximum (10240000))

  Object[] o = this.getActionErrors().toArray();

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

   //System.out.println(o[i].toString());

   String msg = o[i].toString();

   this.jsonString = "{\"failure\":\"true\",\"errorMsg\":\""+msg+"\"}";   

   this.clearActionErrors();

   errorFlag=true;

   try {

    execute();

   } catch (Exception e) {

    e.printStackTrace();

   }   

  }

 }

}


三、config struts.xml:
<?xml version="1.0" encoding="UTF-8"?>

   <!DOCTYPE struts PUBLIC

 "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"

 "http://struts.apache.org/dtds/struts-2.1.dtd">



<struts>

 <constant name="struts.devMode" value="true"></constant> 

 <constant name="struts.configuration.xml.reload" value="true"></constant>

 <constant name="struts.i18n.reload" value="true"></constant>

 <constant name="struts.custom.i18n.resources" value="globalMessages"></constant>


 <!-- temp dir -->

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

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

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

 <package name="ExtStudy" extends="struts-default">

  <action name="SysMgrJson" class="SysMgrJsonAction">

   <result name="functoinJSON">JsonJSP/functionJSON.jsp</result>

   <result name="titleJSON">JsonJSP/titleJSON.jsp</result>

   <result name="comboFormJSON">JsonJSP/comboFormJSON.jsp</result>

   <result name="outputJSON">JsonJSP/outputJSON.jsp</result>

  </action>

  <action name="multiFileUpload" class="com.action.test.MultiFileUploadAction">

            <interceptor-ref name="fileUpload"> 

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

                <param name="allowedTypes">

                 image/png,

                 image/gif,

                 image/jpeg,

                 image/jpg,

                </param>

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

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

            </interceptor-ref> 

            <interceptor-ref name="defaultStack" />   

   <result>JsonJSP/outputJSON.jsp</result>

   <result name="input">Basic/fileUploadForm.jsp</result>

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

  </action> 

 </package>

</struts>

四、測試結果:
1.http://localhost:8080/ExtStudy/Basic/fileUploadForm.jsp


















沒有留言:

張貼留言