1. 程式人生 > >java一款支援批量上傳的程式碼示例

java一款支援批量上傳的程式碼示例

效果圖如下:



該工程包含五個原始檔:BackGroundService.java、BeanControler.java、EventListenerImpl.java、FileUploadListener.java和FileUploadStatus.java;以及2個jsp頁面。原始碼已提供免費下載,下載後直接部署到tomcat中執行即可。

BackGroundService.java:

package liuzuochen.sample.upload;

/**
 * <p>Title: 後臺服務</p>
 *
 * <p>Description: 為客戶端提供上傳及檔案傳輸狀態查詢服務</p>
 *
 */

import java.io.File;
import java.io.IOException;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.*;


public class BackGroundService extends javax.servlet.http.HttpServlet implements
        javax.servlet.Servlet {

    public static final String UPLOAD_DIR = "/upload";
    public static final String DEFAULT_UPLOAD_FAILURE_URL = "index2.jsp";

    public BackGroundService() {
        super();
    }


    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException,
            IOException {
        doPost(request, response);
    }

    /**
     * 從檔案路徑中取出檔名
     */
    private String takeOutFileName(String filePath) {
        int pos = filePath.lastIndexOf(File.separator);
        if (pos > 0) {
            return filePath.substring(pos + 1);
        } else {
            return filePath;
        }
    }

    /**
     * 從request中取出FileUploadStatus Bean
     */
    public static FileUploadStatus getStatusBean(
            HttpServletRequest request) {
        BeanControler beanCtrl = BeanControler.getInstance();
        return beanCtrl.getUploadStatus(request.getRemoteAddr());
    }

    /**
     * 把FileUploadStatus Bean儲存到類控制器BeanControler
     */
    public static void saveStatusBean(
            HttpServletRequest request,
            FileUploadStatus statusBean) {
        statusBean.setUploadAddr(request.getRemoteAddr());
        BeanControler beanCtrl = BeanControler.getInstance();
        beanCtrl.setUploadStatus(statusBean);
    }

    /**
     * 刪除已經上傳的檔案
     */
    private void deleteUploadedFile(HttpServletRequest request) {
        FileUploadStatus satusBean = getStatusBean(request);
        for (int i = 0; i < satusBean.getUploadFileUrlList().size(); i++) {
            File uploadedFile = new File(request.getRealPath(UPLOAD_DIR) +
                                         File.separator +
                                         satusBean.getUploadFileUrlList().
                                         get(i));
            uploadedFile.delete();
        }
        satusBean.getUploadFileUrlList().clear();
        satusBean.setStatus("刪除已上傳的檔案");
        saveStatusBean(request, satusBean);
    }

    /**
     * 上傳過程中出錯處理
     */
    private void uploadExceptionHandle(
            HttpServletRequest request,
            String errMsg) throws ServletException, IOException {
        //首先刪除已經上傳的檔案
        deleteUploadedFile(request);
        FileUploadStatus satusBean = getStatusBean(request);
        satusBean.setStatus(errMsg);
        saveStatusBean(request, satusBean);
    }

    /**
     * 初始化檔案上傳狀態Bean
     */
    private FileUploadStatus initStatusBean(HttpServletRequest
            request) {
        FileUploadStatus satusBean = new FileUploadStatus();
        satusBean.setStatus("正在準備處理");
        satusBean.setUploadTotalSize(request.getContentLength());
        satusBean.setProcessStartTime(System.currentTimeMillis());
        satusBean.setBaseDir(request.getContextPath() + UPLOAD_DIR);
        return satusBean;
    }

    /**
     * 處理檔案上傳
     */
    private void processFileUpload(HttpServletRequest request,
                                   HttpServletResponse response) throws
            ServletException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //設定記憶體緩衝區,超過後寫入臨時檔案
        factory.setSizeThreshold(10240000);
        //設定臨時檔案儲存位置
        factory.setRepository(new File(request.getRealPath("/upload/temp")));
     
        ServletFileUpload upload = new ServletFileUpload(factory);
        //設定單個檔案的最大上傳值
        upload.setFileSizeMax(5*102400000);
        //設定整個request的最大值
        upload.setSizeMax(10*102400000);
        upload.setProgressListener(new FileUploadListener(request));
        //儲存初始化後的FileUploadStatus Bean
        saveStatusBean(request, initStatusBean(request));
        FileUploadStatus satusBean =
            getStatusBean(request);
        String forwardURL = "";
        int flag=1;
        try {
            List items = upload.parseRequest(request);
            //獲得返回url
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (item.isFormField()) {
                    forwardURL = item.getString();
                    break;
                }
            }
           
            //處理檔案上傳
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);

                //取消上傳
                if (getStatusBean(request).getCancel()) {
                    deleteUploadedFile(request);
                    break;
                }
                //儲存檔案
                else if (!item.isFormField() && item.getName().length() > 0) {
                    String fileName = takeOutFileName(item.getName());
                    File uploadedFile = new File(request.getRealPath(UPLOAD_DIR) +
                                                 File.separator + fileName);
                    item.write(uploadedFile);
                    flag++;
                    //更新上傳檔案列表
                   
                    satusBean.getUploadFileUrlList().add(fileName);
                    saveStatusBean(request, satusBean);
                    //Thread.sleep(500);
                }
            }
       
        } catch (FileUploadException e) {
            uploadExceptionHandle(request, "上傳檔案時發生錯誤:" + e.getMessage());
        } catch (Exception e) {
            uploadExceptionHandle(request, "儲存上傳檔案時發生錯誤:" + e.getMessage());
        }
        if (forwardURL.length() == 0) {
            forwardURL = DEFAULT_UPLOAD_FAILURE_URL;
        }
        request.setAttribute("msg", "<font size=2><b>檔案上傳成功!</b></font>");
        request.getRequestDispatcher("index2.jsp").forward(request, response);
    }

    /**
     * 迴應上傳狀態查詢
     */
    private void responseStatusQuery(HttpServletRequest request,
                                              HttpServletResponse response) throws
            IOException {
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        FileUploadStatus satusBean = getStatusBean(request);
        response.setCharacterEncoding("gbk");
        response.getWriter().write(satusBean.toJSon());
    }

    /**
     * 處理取消檔案上傳
     */
    private void processCancelFileUpload(HttpServletRequest request,
                                         HttpServletResponse response) throws
            IOException {
        FileUploadStatus satusBean = getStatusBean(request);
        satusBean.setCancel(true);
        saveStatusBean(request, satusBean);
        responseStatusQuery(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException,
            IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            processFileUpload(request, response);
        } else {
            request.setCharacterEncoding("gbk");

            if (request.getParameter("uploadStatus") != null) {
                responseStatusQuery(request, response);
            }
            if (request.getParameter("cancelUpload") != null) {
                processCancelFileUpload(request, response);
            }

        }
    }
}


BeanControler.java:

package liuzuochen.sample.upload;

/**
 * <p>Title: 類控制器</p>
 *
 * <p>Description: 主要作用是對FileUploadStatus進行管理,為客戶端提供相應的
 * FileUploadStatus類物件。這是一個單例類。</p>
 *
 */
import java.util.Vector;

public class BeanControler {
    private static BeanControler beanControler = new BeanControler();
    private Vector vector = new Vector();
    private BeanControler() {
    }

    public static BeanControler getInstance() {
        return beanControler;
    }

    /**
     * 取得相應FileUploadStatus類物件的儲存位置
     */
    private int indexOf(String strID) {
        int nReturn = -1;
        for (int i = 0; i < vector.size(); i++) {
            FileUploadStatus status = (FileUploadStatus) vector.elementAt(i);
            if (status.getUploadAddr().equals(strID)) {
                nReturn = i;
                break;
            }
        }
        return nReturn;
    }
    /**
     * 取得相應FileUploadStatus類物件
     */
    public FileUploadStatus getUploadStatus(String strID) {
        return (FileUploadStatus) vector.elementAt(indexOf(strID));
    }
    /**
     * 儲存FileUploadStatus類物件
     */
    public void setUploadStatus(FileUploadStatus status) {
        int nIndex = indexOf(status.getUploadAddr());
        if ( -1 == nIndex) {
            vector.add(status);
        } else {
            vector.insertElementAt(status, nIndex);
            vector.removeElementAt(nIndex + 1);
        }
    }
    /**
     * 刪除FileUploadStatus類物件
     */
    public void removeUploadStatus(String strID){
        int nIndex = indexOf(strID);
        if(-1!=nIndex)
            vector.removeElementAt(nIndex);
    }
}


EventListenerImpl.java:

package liuzuochen.sample.upload;

import javax.servlet.http.HttpServletRequest;

import com.enterprisedt.net.ftp.EventListener;
import com.enterprisedt.util.debug.Logger;

public class EventListenerImpl implements EventListener {

	public static long transferedbyte=0;
	public static long totalfilesize=0;
	public static long flag=0;
    private Logger log = Logger.getLogger(EventListenerImpl.class);
    private static int cuNum=0;
    private HttpServletRequest request=null;
    public static long totalReadBytes=0;
    
    public static long totalReadByteses=0;
    public static int numflag=1;
   public EventListenerImpl(int cuNum,long filesize,HttpServletRequest request)
   {
	   EventListenerImpl.totalfilesize=0;
	   EventListenerImpl.transferedbyte=0;
	   EventListenerImpl.flag=0;
	   this.cuNum=cuNum;
	   this.request=request;
	   
	   EventListenerImpl.totalReadBytes=0;
	   
	   this.totalReadBytes=filesize;
       totalReadByteses+=totalReadBytes;
       
   }
   public static void setTotalSize(long temp)
   {
	   EventListenerImpl.totalfilesize=temp;   
   }
    public void bytesTransferred(String connId, String remoteFilename, long bytes) {
       
        EventListenerImpl.transferedbyte=bytes;
        FileUploadStatus statusBean= BackGroundService.getStatusBean(request);
         statusBean.setUploadTotalSize(FileUploadListener.totalFileSize);
		
         
        //讀取完成
	    if (FileUploadListener.totalFileSize ==this.transferedbyte) {
	       statusBean.setStatus("完成對" + FileUploadListener.currentFileNum +"個檔案的FTP處理 " + FileUploadListener.totalFileSize + " bytes.");
	       statusBean.setReadTotalSize(this.transferedbyte);
	       statusBean.setSuccessUploadFileCount(FileUploadListener.currentFileNum);
	       statusBean.setProcessEndTime(System.currentTimeMillis());
	       statusBean.setProcessRunningTime(statusBean.getProcessEndTime());
	       statusBean.setUploadFlag("ftp");
	    //讀取中
	    } else {
	       statusBean.setStatus("當前正在進行第" +cuNum +"個檔案的FTP檔案上傳:已經處理了 " + (bytes+totalReadByteses-totalReadBytes) + " / " + FileUploadListener.totalFileSize+ " bytes.");
	       statusBean.setReadTotalSize(bytes+totalReadByteses-totalReadBytes);
	       statusBean.setCurrentUploadFileNum(cuNum);
	       statusBean.setProcessRunningTime(System.currentTimeMillis());
	       statusBean.setUploadFlag("ftp");
	    }
            BackGroundService.saveStatusBean(request,statusBean);
        
    }
    
    /**
     * Log an FTP command being sent to the server. Not used for SFTP.
     * 
     * @param cmd   command string
     */
    public void commandSent(String connId, String cmd) {
       
    }
    
    /**
     * Log an FTP reply being sent back to the client. Not used for
     * SFTP.
     * 
     * @param reply   reply string
     */
    public void replyReceived(String connId, String reply) {
      
    }
        
    /**
     * Notifies that a download has started
     * 
     * @param remoteFilename   remote file name
     */
    public void downloadStarted(String connId, String remoteFilename) {
      
    }
    
    /**
     * Notifies that a download has completed
     * 
     * @param remoteFilename   remote file name
     */
    public void downloadCompleted(String connId, String remoteFilename) {
       
    }
    
    /**
     * Notifies that an upload has started
     * 
     * @param remoteFilename   remote file name
     */
    public void uploadStarted(String connId, String remoteFilename) {

        EventListenerImpl.transferedbyte=0;
       
    }
    
    /**
     * Notifies that an upload has completed
     * 
     * @param remoteFilename   remote file name
     */
    public void uploadCompleted(String connId, String remoteFilename) {

        EventListenerImpl.transferedbyte=0;
        EventListenerImpl.totalfilesize=0;
        EventListenerImpl.flag=-1;
    }
    public static long returnFlag()
    {
    	return EventListenerImpl.flag;
    }
	public static long getTransferedbyte() {
		return transferedbyte;
	}

	
	public static long getTotalfilesize() {
		return totalfilesize;
	}
}


FileUploadListener.java:

package liuzuochen.sample.upload;

import org.apache.commons.fileupload.ProgressListener;
import javax.servlet.http.HttpServletRequest;

public class FileUploadListener implements ProgressListener{
	private HttpServletRequest request=null;
	public FileUploadListener(HttpServletRequest request){
		this.request=request;
	}
    public static int currentFileNum=0;
    public static long totalFileSize=0;
	/**
	 * 更新狀態
	 */
	public void update(long pBytesRead, long pContentLength, int pItems){
		FileUploadStatus statusBean= BackGroundService.getStatusBean(request);
		statusBean.setUploadTotalSize(pContentLength);
		EventListenerImpl.setTotalSize(pContentLength);
        //讀取完成
	    if (pContentLength == -1) {
	       statusBean.setStatus("完成對" + pItems +"個檔案的讀取:讀取了 " + pBytesRead + " bytes.");
	       statusBean.setReadTotalSize(pBytesRead);
	       statusBean.setSuccessUploadFileCount(pItems);
	       statusBean.setProcessEndTime(System.currentTimeMillis());
	       statusBean.setProcessRunningTime(statusBean.getProcessEndTime());
	       statusBean.setUploadFlag("http");
	    //讀取中
	    } else {
	       statusBean.setStatus("當前正在處理第" +(pItems+1)/3 +"個檔案的客戶端上傳:已經讀取了 " + pBytesRead + " / " + pContentLength+ " bytes.");
	       statusBean.setReadTotalSize(pBytesRead);
	       statusBean.setCurrentUploadFileNum((pItems+1)/3);
	       statusBean.setProcessRunningTime(System.currentTimeMillis());
	       statusBean.setUploadFlag("http");
	    }
        BackGroundService.saveStatusBean(request,statusBean);
	}
}


FileUploadStatus.java:

package liuzuochen.sample.upload;

import java.util.*;

public class FileUploadStatus {
    //上傳使用者地址
    private String uploadAddr;
    //上傳總量
    private long uploadTotalSize = 0;
    //讀取上傳總量
    private long readTotalSize = 0;
    //當前上傳檔案號
    private int currentUploadFileNum = 0;
    //成功讀取上傳檔案數
    private int successUploadFileCount = 0;
    //狀態
    private String status = "";
    //處理起始時間
    private long processStartTime = 0l;
    //處理終止時間
    private long processEndTime = 0l;
    //處理執行時間
    private long processRunningTime = 0l;
    //上傳檔案URL列表
    private List uploadFileUrlList = new ArrayList();
    //取消上傳
    private boolean cancel = false;
    //上傳base目錄
    private String baseDir = "";

    private String uploadFlag="";
    public FileUploadStatus() {

    }

    public String getBaseDir() {
        return baseDir;
    }

    public void setBaseDir(String baseDir) {
        this.baseDir = baseDir;
    }

    public boolean getCancel() {
        return cancel;
    }

    public void setCancel(boolean cancel) {
        this.cancel = cancel;
    }

    public List getUploadFileUrlList() {
        return uploadFileUrlList;
    }

    public void setUploadFileUrlList(List uploadFileUrlList) {
        this.uploadFileUrlList = uploadFileUrlList;
    }

    public long getProcessRunningTime() {
        return processRunningTime;
    }

    public void setProcessRunningTime(long processRunningTime) {
        this.processRunningTime = processRunningTime;
    }

    public long getProcessEndTime() {
        return processEndTime;
    }

    public void setProcessEndTime(long processEndTime) {
        this.processEndTime = processEndTime;
    }

    public long getProcessStartTime() {
        return processStartTime;
    }

    public void setProcessStartTime(long processStartTime) {
        this.processStartTime = processStartTime;
    }

    public long getReadTotalSize() {
        return readTotalSize;
    }

    public void setReadTotalSize(long readTotalSize) {
        this.readTotalSize = readTotalSize;
    }

    public int getSuccessUploadFileCount() {
        return successUploadFileCount;
    }

    public void setSuccessUploadFileCount(int successUploadFileCount) {
        this.successUploadFileCount = successUploadFileCount;
    }

    public int getCurrentUploadFileNum() {
        return currentUploadFileNum;
    }

    public void setCurrentUploadFileNum(int currentUploadFileNum) {
        this.currentUploadFileNum = currentUploadFileNum;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public long getUploadTotalSize() {
        return uploadTotalSize;
    }

    public String getUploadAddr() {
        return uploadAddr;
    }

    public void setUploadTotalSize(long uploadTotalSize) {
        this.uploadTotalSize = uploadTotalSize;
    }

    public void setUploadAddr(String uploadAddr) {
        this.uploadAddr = uploadAddr;
    }

    public String toJSon() {
        StringBuffer strJSon = new StringBuffer();
        strJSon.append("{UploadTotalSize:").append(getUploadTotalSize()).append(
                ",")
                .append("ReadTotalSize:").append(getReadTotalSize()).append(",")
                .append("CurrentUploadFileNum:").append(getCurrentUploadFileNum()).
                append(",")
                .append("SuccessUploadFileCount:").append(
                        getSuccessUploadFileCount()).append(",")
                .append("Status:'").append(getStatus()).append("',")
                .append("ProcessStartTime:").append(getProcessStartTime()).
                append(",")
                append("',")
                .append("Cancel:").append(getCancel()).append("}");
        
        return strJSon.toString();

    }

	public String getUploadFlag() {
		return uploadFlag;
	}

	public void setUploadFlag(String uploadFlag) {
		this.uploadFlag = uploadFlag;
	}


}


主頁面index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'index.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">
	-->
	<style>
body { background: #ffffff; color: #444; }
a { color: #07c; text-decoration: none; border: 0; background-color: transparent; }
body, div, q, iframe, form, h5 { margin: 0; padding: 0; }
img, fieldset { border: none 0; }
body, td, textarea { word-break: break-all; word-wrap: break-word; line-height:1.6; }
body, input, textarea, select, button { margin: 0; font-size: 14px; font-family: Tahoma, SimSun, sans-serif; }
div, p, table, th, td { font-size:1em; font-family:inherit; line-height:inherit; }
h5 { font-size:12px; }
ol li,ul li{ margin-bottom:0.5em;}
pre, code { font-family: "Courier New", Courier, monospace; word-wrap:break-word; line-height:1.4; font-size:12px;}
pre{background:#f6f6f6; border:#eee solid 1px; margin:1em 0.5em; padding:0.5em 1em;}
#content { padding-left:50px; padding-right:50px; }
#content h2 { font-size:20px; color:#069; padding-top:8px; margin-bottom:8px; }
#content h3 { margin:8px 0; font-size:14px; COLOR:#693; }
#content h4 { margin:8px 0; font-size:16px; COLOR:#690; }
#content div.item { margin-top:10px; margin-bottom:10px; border:#eee solid 4px; padding:10px; }
hr { clear:both; margin:7px 0; +margin: 0;
border:0 none; font-size: 1px; line-height:1px; color: #069; background-color:#069; height: 1px; }
.infobar { background:#fff9e3; border:1px solid #fadc80; color:#743e04; }
</style>
<script type="text/javascript" src="zDrag.js"></script>
<script type="text/javascript" src="zDialog.js"></script>
<script type="text/javascript">
  var diag;
  var initHeight=180;
  function openWindow()
  {
    diag   = new Dialog();
	diag.Width = 680;
	diag.Height = initHeight;
	diag.Title = "檔案上傳視窗";
	diag.URL = "index2.jsp";
	diag.show();
  }
  function addHeight()
  {
    diag.setSize(680,initHeight+30);
    initHeight=initHeight+30;
  }
  function decreaseHeight()
  {
    diag.setSize(680,initHeight-30);
    initHeight=initHeight-30;
  }
  function closeWindow()
  {
    diag.close();
  }
  function resizeHeight()
  {
    initHeight=180;
    diag.setSize(680,180);
  }
  function addProgressHeight()
  {
    diag.setSize(680,initHeight+80);
  }
</script>
  </head>
  
  <body>
    <input type="button" value="上傳檔案" onclick="openWindow();"/> 
  </body>
</html>

上傳處理頁面index2.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
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 'index.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">
	-->
	<script type="text/javascript" src="zDrag.js"></script>
<script type="text/javascript" src="zDialog.js"></script>
	 <script type="text/javascript" src="./javascript/prototype.js"  charset="utf-8"></script>
   <script type="text/javascript" src="./javascript/AjaxWrapper.js" charset="utf-8"></script>
   <link href="./css/fileUpload.css" type="text/css" rel="stylesheet"/>
    <style type="text/css">
      div#readme{
         width:100%;padding:3px 0;background: #BAFB80;
               background-image: url("images/info_32.png");
               background-repeat: no-repeat;
               text-align: center;
    font:85%/1.45 "Lucida Sans Unicode","Lucida Grande",Arial,sans-serif;
    font-size:medium;
    font-weight: bold;
    line-height: 25px;
    height: 25px;
    color:gray;
         
            }
            
    </style>
<style>


</style>
<script type="text/javascript">
  var flag=1;
  function getFileSize(fileSize)
	{
		var num = new Number();
		var unit = '';
		
		if (fileSize > 1*1024*1024*1024){
			num = fileSize/1024/1024/1024;
			unit = "G"
		}
		else if (fileSize > 1*1024*1024){
			num = fileSize/1024/1024;
			unit = "M"			
		}
		else if (fileSize > 1*1024){
			num = fileSize/1024;
			unit = "K"
		}
		else{
			return fileSize;
		}
		
		return num.toFixed(2) + unit;
		
	}	
  function addRow()
  {
  
     if(flag>4)
     {
       Dialog.alert('<font size=2><b>一次最多上傳5個檔案!</b></font>');
       
       return;
     }
  
     var form=document.getElementById('tool');
     
     var text1 = document.createElement("input");
	 text1.size = "60";
	 text1.type = "text";
	 text1.name = "txt"+flag+1;
	 text1.id = "txt"+flag+1;
     text1.className='input_text';
     
     var btn1=  document.createElement("input");
     btn1.name='uploadfile'+flag+1;
     btn1.id='uploadfile'+flag+1;
     btn1.size=40;
     btn1.value='瀏覽...';
     btn1.className="uploadfile2";
     btn1.hidefocus='';
     
     var inputNode1 = document.createElement("input");
	 inputNode1.size = "30";
	 inputNode1.type = "file";
	 inputNode1.name = "file"+flag+1;
	 inputNode1.id = "file"+flag+1;
	 inputNode1.className='input_file';
	 
	 
     if(inputNode1.addEventListener)
	{
					inputNode1.addEventListener("change",changeValue(text1,inputNode1),false);
	}
	else if(inputNode1.attachEvent)
	{
				
					inputNode1.attachEvent("onchange", changeValue(text1,inputNode1)) ;
	}	
	
	 var inputNode3 = document.createElement("a");
	 inputNode3.href = "javascript:void(0);";
	 
	 
	 var img=document.createElement("img");
	 img.src='images/delete.png';
	 img.width=28;
	 img.height=28;
	 img.border='0';
	 img.className='imgstyle';
	 img.alt='刪除一行';
	 inputNode3.appendChild(img);
	 
	 if(inputNode3.addEventListener)
	{
					inputNode3.addEventListener("click",deleterow(form,text1,btn1,inputNode1,inputNode3),false);
	}
	else if(inputNode3.attachEvent)
	{
				
					inputNode3.attachEvent("onclick", deleterow(form,text1,btn1,inputNode1,inputNode3)) ;
	}
	 
	 form.appendChild(text1);
	 form.appendChild(btn1);
	 form.appendChild(inputNode1);
	 form.appendChild(inputNode3);
	 flag++;
	 
	 parent.addHeight();
	 
  }

  var changeValue=function changeValue(v1,v2)
  {
     return function()
     {
        v1.value=v2.value;
     }
  }
 function init()
  {
     var btn1=document.getElementById('uploadfile2');
     btn1.size=40;
     btn1.value='瀏覽...';
     btn1.className="uploadfile2";
     
  }
  var deleterow = function(form,text1,btn1,inputNode1,inputNode3){
				 return function(){
				    form.removeChild(text1);
      form.removeChild(btn1);
      form.removeChild(inputNode1);
      form.removeChild(inputNode3);
      flag--;
      parent.decreaseHeight();
	}
  }
  function closeWindow()
  {
     parent.closeWindow();
  }
</script>
  </head>
  <body onload="init();">
  <div id="controlPanel">
	<div id="readme">說明:  最大上傳量:1000M,單個檔案最大容量:100M</div>
	<div id="uploadFileUrl"></div>
	<form id="fileUploadForm" name="fileUploadForm" action="./BackGroundService.action" 
		enctype="multipart/form-data" method="post">
	<input class="input_text" type="text" id="txt1" name="txt1" size="60"/><input type="button" name="uploadfile2"  id="uploadfile2" style="padding-left: 26px;"/><input class="input_file" size="30" type="file" name="file1" id="file1" hidefocus onchange="txt1.value=this.value"/><a href="javascript:void(0);"  onclick="addRow();"><img src="images/add.png" width="28" height="28" border="0" alt="新增一行" class="imgstyle"/></a><br>
	<div id="tool">
	</div>
	<br>
	<input type="submit" name="uploadButton" id="uploadButton" value="開始上傳" class="up_btn"/>
	<input type="button" name="cancelUploadButton" onclick="closeWindow();" id="cancelUploadButton" value="取消上傳" class="up_btn"/><br>
	</form>
	
	<div id="progressBar">
	<div id="theMeter">
    	<div id="progressBarText"></div>
	        <div id="totalProgressBarBox">
	        	<div id="totalProgressBarBoxContent"></div>
	        </div>
        </div>
        <div id="progressStatusText"></div>
   </div>
   
</div>
<script>
Element.hide('progressBar');
Event.observe('fileUploadForm','submit',startProgress,false);
Event.observe('cancelUploadButton','click',cancelProgress,false);

//重新整理上傳狀態
function refreshUploadStatus(){
	var ajaxW = new AjaxWrapper(false);
	ajaxW.putRequest(
		'./BackGroundService.action',
		'uploadStatus=',
		function(responseText){
				eval("uploadInfo = " + responseText);
				var progressPercent = Math.ceil(
					(uploadInfo.ReadTotalSize) / uploadInfo.UploadTotalSize * 100);
	
				if(uploadInfo.UploadFlag=='http'){
				   flag='(HTTP狀態)';
				   
				}else
				{
				   flag='(FTP狀態)';
				}
				
				$('progressBarText').innerHTML=flag;
				$('progressBarText').innerHTML += ' 上傳處理進度: '+progressPercent+'% 【'+
					getFileSize(uploadInfo.ReadTotalSize)+'/'+getFileSize(uploadInfo.UploadTotalSize) +
					'】 正在處理第'+uploadInfo.CurrentUploadFileNum+'個檔案'+
					' 耗時: '+(uploadInfo.ProcessRunningTime-uploadInfo.ProcessStartTime)+' ms';
					
				$('progressStatusText').innerHTML=' 反饋狀態: '+uploadInfo.Status;
				$('totalProgressBarBoxContent').style.width = parseInt(progressPercent * 3.5) + 'px';
		}
	);
}
//上傳處理
function startProgress(){
    parent.addProgressHeight();
	Element.show('progressBar');
    $('progressBarText').innerHTML = ' 上傳處理進度: 0%';
    $('progressStatusText').innerHTML=' 反饋狀態:';
    $('uploadButton').disabled = true;
    $('cancelUploadButton').disabled = true;
    var periodicalExe=new PeriodicalExecuter(refreshUploadStatus,0.5);
    return true;
}
//取消上傳處理
function cancelProgress(){
	$('cancelUploadButton').disabled = true;
	var ajaxW = new AjaxWrapper(false);
	ajaxW.putRequest(
		'./BackGroundService.action',
		'cancelUpload=true',
		//因為form的提交,這可能不會執行
		function(responseText){
			eval("uploadInfo = " + responseText);
			$('progressStatusText').innerHTML=' 反饋狀態: '+uploadInfo.status;
			if (msgInfo.cancel=='true'){
				alert('刪除成功!');
				window.location.reload();
			};
		}
	);
}
</script>
<%
String msg=(String)request.getAttribute("msg");
if(msg!=null&&msg.length()>0)
{
   %>
   <script type="text/javascript">
      Dialog.alert('<%=msg%>');
      parent.resizeHeight();
      
   </script>
   
   <%
}
 %>
  </body>
</html>
原始碼下載地址:http://download.csdn.net/detail/xuweilinjijis/5160835