使用uploadify進行上傳

 
Html代碼 複製代碼 收藏代碼
  1. <html>  
  2. <bead>  
  3. <link href="${cssPath}/uploadify.css" rel="stylesheet" type="text/css" />  
  4. <script language="javascript" type="text/javascript"  
  5.     src="${jsPath}/jquery-1.3.2.js"></script>  
  6. <script type="text/javascript" src="${jsPath}/uploadify/swfobject.js"></script>  
  7. <script type="text/javascript" src="${jsPath}/uploadify/jquery.uploadify.v2.1.0.min.js"></script>  
  8. <script language="javascript" type="text/javascript">  
  9. $(document).ready(function() {   
  10.     $("#uploadify").uploadify({   
  11.         'uploader'        : '${jsPath}/uploadify/uploadify.swf',   
  12.         'script'              : '${actionPath}/servlet/Upload',   
  13.         'cancelImg'       : '${cssPath}/images/uploadify/cancel.png',   
  14.         'auto'                : true,   
  15.         'multi'                : false,   
  16.         'fileExt'        : '*.xls',   
  17.         'fileDesc'       : '請選擇Execl文件(*.xls)',   
  18.         'fileDataName'   : 'uploadify',   
  19.         'onComplete'     : function(event,queueId,fileObj,response,data){   
  20.                                 $("#message").text(response);   
  21.                                 setInterval($('#uploadify').uploadifyClearQueue() , 2000);   
  22.                            }   
  23.     });   
  24. });   
  25. </script>  
  26. </head>  
  27. <body>  
  28. <div id="fileQueue"></div>  
  29.     <input type="file" name="uploadify" id="uploadify" />  
  30. </body>  
  31. </html>  
<html>
<bead>
<link href="${cssPath}/uploadify.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript"
	src="${jsPath}/jquery-1.3.2.js"></script>
<script type="text/javascript" src="${jsPath}/uploadify/swfobject.js"></script>
<script type="text/javascript" src="${jsPath}/uploadify/jquery.uploadify.v2.1.0.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
    $("#uploadify").uploadify({
        'uploader'        : '${jsPath}/uploadify/uploadify.swf',
        'script'              : '${actionPath}/servlet/Upload',
        'cancelImg'       : '${cssPath}/images/uploadify/cancel.png',
        'auto'                : true,
        'multi'                : false,
        'fileExt'		 : '*.xls',
        'fileDesc'		 : '請選擇Execl文件(*.xls)',
        'fileDataName'   : 'uploadify',
        'onComplete'	 : function(event,queueId,fileObj,response,data){
            					$("#message").text(response);
            					setInterval($('#uploadify').uploadifyClearQueue() , 2000);
        				   }
    });
});
</script>
</head>
<body>
<div id="fileQueue"></div>
    <input type="file" name="uploadify" id="uploadify" />
</body>
</html>

uploader : uploadify.swf 文件的相對路徑,該swf文件是一個帶有文字BROWSE的按鈕,點擊後淡出打開文件對話框,默認值:uploadify.swf。
script :   後臺處理程序的相對路徑 。默認值:uploadify.php
checkScript :用來判斷上傳選擇的文件在服務器是否存在的後臺處理程序的相對路徑
fileDataName :設置一個名字,在服務器處理程序中根據該名字來取上傳文件的數據。默認爲Filedata
method : 提交方式Post 或Get 默認爲Post
scriptAccess : flash腳本文件的訪問模式,如果在本地測試設置爲always,默認值:sameDomain 
folder :   上傳文件存放的目錄 。
queueID : 文件隊列的ID,該ID與存放文件隊列的div的ID一致。
queueSizeLimit : 當允許多文件生成時,設置選擇文件的個數,默認值:999 。
multi : 設置爲true時可以上傳多個文件。
auto : 設置爲true當選擇文件後就直接上傳了,爲false需要點擊上傳按鈕才上傳 。
fileDesc : 這個屬性值必須設置fileExt屬性後纔有效,用來設置選擇文件對話框中的提示文本,如設置fileDesc爲“請選擇rar doc pdf文件”

fileExt : 設置可以選擇的文件的類型,格式如:'*.doc;*.pdf;*.rar' 。
sizeLimit : 上傳文件的大小限制 。
simUploadLimit : 允許同時上傳的個數 默認值:1 。
buttonText : 瀏覽按鈕的文本,默認值:BROWSE 。
buttonImg : 瀏覽按鈕的圖片的路徑 。
hideButton : 設置爲true則隱藏瀏覽按鈕的圖片 。
rollover : 值爲true和false,設置爲true時當鼠標移到瀏覽按鈕上時有反轉效果。
width : 設置瀏覽按鈕的寬度 ,默認值:110。
height : 設置瀏覽按鈕的高度 ,默認值:30。
wmode : 設置該項爲transparent 可以使瀏覽按鈕的flash背景文件透明,並且flash文件會被置爲頁面的最高層。 默認值:opaque 。
cancelImg :選擇文件到文件隊列中後的每一個文件上的關閉按鈕圖標

上面介紹的key值的value都爲字符串或是布爾類型,比較簡單,接下來要介紹的key值的value爲一個函數,可以在選擇文件、出錯或其他一些操作的時候返回一些信息給用戶。

onInit : 做一些初始化的工作

onSelect : 選擇文件時觸發,該函數有三個參數

  • event:事件對象。
  • queueID:文件的唯一標識,由6爲隨機字符組成。
  • fileObj:選擇的文件對象,有name、size、creationDate、modificationDate、type 5個屬性。

onSelectOnce :在單文件或多文件上傳時,選擇文件時觸發。該函數有兩個參數event,data,data對象有以下幾個屬性:

fileCount:選擇文件的總數。
filesSelected:同時選擇文件的個數,如果一次選擇了3個文件該屬性值爲3。
filesReplaced:如果文件隊列中已經存在A和B兩個文件,再次選擇文件時又選擇了A和B,該屬性值爲2。
allBytesTotal:所有選擇的文件的總大小。

onCancel : 當點擊文件隊列中文件的關閉按鈕或點擊取消上傳時觸發。該函數有event、queueId、fileObj、data四個參數,前三個參數同 onSelect 中的三個參數,data對象有兩個屬性fileCount和allBytesTotal。

fileCount:取消一個文件後,文件隊列中剩餘文件的個數。
allBytesTotal:取消一個文件後,文件隊列中剩餘文件的大小。

onClearQueue :當調用函數fileUploadClearQueue時觸發。有event和data兩個參數,同onCancel 中的兩個對應參數。

onQueueFull :當設置了queueSizeLimit並且選擇的文件個數超出了queueSizeLimit的值時觸發。該函數有兩個參數event和queueSizeLimit。

onError :當上傳過程中發生錯誤時觸發。該函數有event、queueId、fileObj、errorObj四個參數,其中前三個參數同上,errorObj對象有type和info兩個屬性。

type:錯誤的類型,有三種‘HTTP’, ‘IO’, or ‘Security’
info:錯誤的描述

onOpen :點擊上傳時觸發,如果auto設置爲true則是選擇文件時觸發,如果有多個文件上傳則遍歷整個文件隊列。該函數有event、queueId、fileObj三個參數,參數的解釋同上。

onProgress :點擊上傳時觸發,如果auto設置爲true則是選擇文件時觸發,如果有多個文件上傳則遍歷整個文件隊列,在onOpen之後觸發。該函數有 event、queueId、fileObj、data四個參數,前三個參數的解釋同上。data對象有四個屬性percentage、 bytesLoaded、allBytesLoaded、speed:

percentage:當前完成的百分比
bytesLoaded:當前上傳的大小
allBytesLoaded:文件隊列中已經上傳完的大小
speed:上傳速率 kb/s

onComplete:文件上傳完成後觸發。該函數有四個參數event、queueId、fileObj、response、data五個參數,前三個參數同上。response爲後臺處理程序返回的值,在上面的例子中爲1或0,data有兩個屬性fileCount和speed

fileCount:剩餘沒有上傳完成的文件的個數。
speed:文件上傳的平均速率 kb/s
注:fileObj對象和上面講到的有些不太一樣,onComplete 的fileObj對象有個filePath屬性可以取出上傳文件的路徑。

 

onAllComplete:文件隊列中所有的文件上傳完成後觸發。該函數有event和data兩個參數,data有四個屬性,分別爲:

filesUploaded :上傳的所有文件個數。
errors :出現錯誤的個數。
allBytesLoaded :所有上傳文件的總大小。
speed :平均上傳速率 kb/s

 

我這個HTML文件使用的是自動上傳

如要進行手動上傳,修改屬性,自己手動調用JS

Html代碼 複製代碼 收藏代碼
  1. <a href="javascript:$('#uploadify').uploadifyUpload()">上傳</a>|    
  2.       <a href="javascript:$('#uploadify').uploadifyClearQueue()">取消上傳</a>  
  3.       
<a href="javascript:$('#uploadify').uploadifyUpload()">上傳</a>| 
      <a href="javascript:$('#uploadify').uploadifyClearQueue()">取消上傳</a>
    
 

servlet代碼:

Java代碼 複製代碼 收藏代碼
  1. import java.io.File;   
  2. import java.io.IOException;   
  3. import java.io.PrintWriter;   
  4. import java.util.Iterator;   
  5. import java.util.List;   
  6.   
  7. import javax.servlet.ServletException;   
  8. import javax.servlet.http.HttpServlet;   
  9. import javax.servlet.http.HttpServletRequest;   
  10. import javax.servlet.http.HttpServletResponse;   
  11.   
  12. import org.apache.commons.fileupload.FileItem;   
  13. import org.apache.commons.fileupload.FileUploadException;   
  14. import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;   
  15. import org.apache.commons.fileupload.disk.DiskFileItemFactory;   
  16. import org.apache.commons.fileupload.servlet.ServletFileUpload;   
  17.   
  18. import com.etraveltek.lps.utils.Constants;   
  19.   
  20. public class TransactionUploadServlet extends HttpServlet {   
  21.   
  22.     protected void doPost(HttpServletRequest request,   
  23.             HttpServletResponse response) throws ServletException, IOException {   
  24.         String transactionImportTemp = (String) request.getSession()   
  25.                 .getServletContext().getAttribute(   
  26.                         Constants.TRANSACTION_IMPORT_TEMP);   
  27.   
  28.         // 設置上傳文件最大爲 3M   
  29.         final long MAX_SIZE = 3 * 1024 * 1024;   
  30.         // 允許上傳的文件格式的列表 final   
  31.         String[] allowedExt = new String[] { "xls" };   
  32.   
  33.         response.setContentType("text/html"); // 設置字符編碼爲UTF-8, 這樣支持漢字顯示   
  34.         response.setCharacterEncoding("UTF-8");   
  35.   
  36.         // 實例化一個硬盤文件工廠,用來配置上傳組件   
  37.         DiskFileItemFactory dfif = new DiskFileItemFactory();   
  38.         // 設置上傳文件時用於臨時存放文件的內存大小,這裏是4K.多於的部分將臨時存在硬盤   
  39.         dfif.setSizeThreshold(4096); // 設置存放臨時文件的目錄,web根目錄下的ImagesUploadTemp目錄   
  40.         File tmpFile = new File(transactionImportTemp);   
  41.         if (!tmpFile.exists()) {   
  42.             tmpFile.mkdirs();   
  43.         }   
  44.         dfif.setRepository(tmpFile);   
  45.   
  46.         // 用以上工廠實例化上傳組件   
  47.         ServletFileUpload sfu = new ServletFileUpload(dfif);   
  48.         // 設置最大上傳尺寸   
  49.         sfu.setSizeMax(MAX_SIZE);   
  50.   
  51.         PrintWriter out = response.getWriter();   
  52.         // 從request得到 所有 上傳域的列表   
  53.         List fileList = null;   
  54.         try {   
  55.             fileList = sfu.parseRequest(request);   
  56.         } catch (FileUploadException e) {   
  57.             // 處理文件尺寸過大異常   
  58.             e.printStackTrace();   
  59.             if (e instanceof SizeLimitExceededException) {   
  60.                 out.println("文件尺寸超過規定大小:" + MAX_SIZE + "字節<p />");   
  61.                 out.println("<a href=\"upload.html\" target=\"_top\">返回</a>"); //   
  62.                 e.printStackTrace();   
  63.                 return;   
  64.             }   
  65.         }   
  66.   
  67.         // 沒有文件上傳   
  68.         if (fileList == null || fileList.size() == 0) {   
  69.             out.println("請選擇上傳文件<p />");   
  70.             out.println("<a href=\"upload.html\" target=\"_top\">返回</a>"); //    
  71.             return;   
  72.         }   
  73.   
  74.         // 得到所有上傳的文件   
  75.         Iterator fileItr = fileList.iterator(); // 循環處理所有文件   
  76.         while (fileItr.hasNext()) {   
  77.             FileItem fileItem = null;   
  78.             String path = null;   
  79.             long size = 0;   
  80.             // 得到當前文件   
  81.             fileItem = (FileItem) fileItr.next();   
  82.             // 忽略簡單form字段而不是上傳域的文件域(<input type="text" />等)   
  83.             if (fileItem == null || fileItem.isFormField()) {   
  84.                 continue// 得到文件的完整路徑   
  85.             }   
  86.             path = fileItem.getName();   
  87.             // 得到文件的大小   
  88.             size = fileItem.getSize();   
  89.             if ("".equals(path) || size == 0) {   
  90.                 out.println("請選擇上傳文件<p />");   
  91.                 out.println("<a href=\"upload.html\" target=\"_top\">返回</a>"); // return;   
  92.             }   
  93.   
  94.             // 得到去除路徑的文件名   
  95.             String t_name = path.substring(path.lastIndexOf("\\") + 1);   
  96.             // 得到文件的擴展名(無擴展名時將得到全名)   
  97.             String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);   
  98.             // 拒絕接受規定文件格式之外的文件類型   
  99.             int allowFlag = 0;   
  100.             int allowedExtCount = allowedExt.length;   
  101.             for (; allowFlag < allowedExtCount; allowFlag++) {   
  102.                 if (allowedExt[allowFlag].equals(t_ext)) {   
  103.                     break;   
  104.                 }   
  105.             }   
  106.             if (allowFlag == allowedExtCount) {   
  107.                 out.println("請上傳以下類型的文件<p />");   
  108.                 for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++) {   
  109.                     out.println("*." + allowedExt[allowFlag]   
  110.                             + "&nbsp;&nbsp;&nbsp;");   
  111.                     out   
  112.                             .println("<p /><a href=\"upload.html\" target=\"_top\">返回</a>"); // return;   
  113.                 }   
  114.             }   
  115.   
  116.             // long now = System.currentTimeMillis();   
  117.             // 根據系統時間生成上傳後保存的文件名   
  118.             // String prefix = String.valueOf(now);   
  119.             // 保存的最終文件完整路徑,保存在web根目錄下的ImagesUploaded目錄下   
  120.             // String u_name = transactionImportTemp + prefix + "." + t_ext;   
  121.             try { // 保存文件   
  122.                 fileItem.write(new File(t_name));   
  123.                 out.println("文件上傳成功。已保存爲:" + t_name + "。");   
  124.             } catch (Exception e) {   
  125.                 e.printStackTrace();   
  126.             }   
  127.         }   
  128.     }   
  129.   
  130.     @Override  
  131.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)   
  132.             throws ServletException, IOException {   
  133.         // TODO Auto-generated method stub   
  134.         super.doGet(req, resp);   
  135.     }   
  136.   
  137.     private void delTempFile(String tempFilePath) {   
  138.   
  139.         File tempFile = new File(tempFilePath);   
  140.   
  141.         if (tempFile.exists() && tempFile.isDirectory()) {   
  142.             File[] allFile = tempFile.listFiles();   
  143.             for (File file : allFile) {   
  144.                 String fileName = file.getName();   
  145.                 String ext = fileName.substring(fileName.lastIndexOf(".") + 1);   
  146.                 if (ext == null || ext.trim().length() == 0) {   
  147.                     continue;   
  148.                 }   
  149.                 for (String tmpExt : Constants.TRANSACTION_IMPORT_TEMP_EXT) {   
  150.                     if (ext.equals(tmpExt)) {   
  151.                         file.delete();   
  152.                     }   
  153.                 }   
  154.             }   
  155.         }   
  156.   
  157.     }   
  158.   
  159.     public static void main(String[] args) {   
  160.         new TransactionUploadServlet()   
  161.                 .delTempFile("D:\\tmp\\file\\TransactionImportTemp");   
  162.     }   
  163. }  
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
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.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.etraveltek.lps.utils.Constants;

public class TransactionUploadServlet extends HttpServlet {

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String transactionImportTemp = (String) request.getSession()
				.getServletContext().getAttribute(
						Constants.TRANSACTION_IMPORT_TEMP);

		// 設置上傳文件最大爲 3M
		final long MAX_SIZE = 3 * 1024 * 1024;
		// 允許上傳的文件格式的列表 final
		String[] allowedExt = new String[] { "xls" };

		response.setContentType("text/html"); // 設置字符編碼爲UTF-8, 這樣支持漢字顯示
		response.setCharacterEncoding("UTF-8");

		// 實例化一個硬盤文件工廠,用來配置上傳組件
		DiskFileItemFactory dfif = new DiskFileItemFactory();
		// 設置上傳文件時用於臨時存放文件的內存大小,這裏是4K.多於的部分將臨時存在硬盤
		dfif.setSizeThreshold(4096); // 設置存放臨時文件的目錄,web根目錄下的ImagesUploadTemp目錄
		File tmpFile = new File(transactionImportTemp);
		if (!tmpFile.exists()) {
			tmpFile.mkdirs();
		}
		dfif.setRepository(tmpFile);

		// 用以上工廠實例化上傳組件
		ServletFileUpload sfu = new ServletFileUpload(dfif);
		// 設置最大上傳尺寸
		sfu.setSizeMax(MAX_SIZE);

		PrintWriter out = response.getWriter();
		// 從request得到 所有 上傳域的列表
		List fileList = null;
		try {
			fileList = sfu.parseRequest(request);
		} catch (FileUploadException e) {
			// 處理文件尺寸過大異常
			e.printStackTrace();
			if (e instanceof SizeLimitExceededException) {
				out.println("文件尺寸超過規定大小:" + MAX_SIZE + "字節<p />");
				out.println("<a href=\"upload.html\" target=\"_top\">返回</a>"); //
				e.printStackTrace();
				return;
			}
		}

		// 沒有文件上傳
		if (fileList == null || fileList.size() == 0) {
			out.println("請選擇上傳文件<p />");
			out.println("<a href=\"upload.html\" target=\"_top\">返回</a>"); // 
			return;
		}

		// 得到所有上傳的文件
		Iterator fileItr = fileList.iterator(); // 循環處理所有文件
		while (fileItr.hasNext()) {
			FileItem fileItem = null;
			String path = null;
			long size = 0;
			// 得到當前文件
			fileItem = (FileItem) fileItr.next();
			// 忽略簡單form字段而不是上傳域的文件域(<input type="text" />等)
			if (fileItem == null || fileItem.isFormField()) {
				continue; // 得到文件的完整路徑
			}
			path = fileItem.getName();
			// 得到文件的大小
			size = fileItem.getSize();
			if ("".equals(path) || size == 0) {
				out.println("請選擇上傳文件<p />");
				out.println("<a href=\"upload.html\" target=\"_top\">返回</a>"); // return;
			}

			// 得到去除路徑的文件名
			String t_name = path.substring(path.lastIndexOf("\\") + 1);
			// 得到文件的擴展名(無擴展名時將得到全名)
			String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
			// 拒絕接受規定文件格式之外的文件類型
			int allowFlag = 0;
			int allowedExtCount = allowedExt.length;
			for (; allowFlag < allowedExtCount; allowFlag++) {
				if (allowedExt[allowFlag].equals(t_ext)) {
					break;
				}
			}
			if (allowFlag == allowedExtCount) {
				out.println("請上傳以下類型的文件<p />");
				for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++) {
					out.println("*." + allowedExt[allowFlag]
							+ "&nbsp;&nbsp;&nbsp;");
					out
							.println("<p /><a href=\"upload.html\" target=\"_top\">返回</a>"); // return;
				}
			}

			// long now = System.currentTimeMillis();
			// 根據系統時間生成上傳後保存的文件名
			// String prefix = String.valueOf(now);
			// 保存的最終文件完整路徑,保存在web根目錄下的ImagesUploaded目錄下
			// String u_name = transactionImportTemp + prefix + "." + t_ext;
			try { // 保存文件
				fileItem.write(new File(t_name));
				out.println("文件上傳成功。已保存爲:" + t_name + "。");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	private void delTempFile(String tempFilePath) {

		File tempFile = new File(tempFilePath);

		if (tempFile.exists() && tempFile.isDirectory()) {
			File[] allFile = tempFile.listFiles();
			for (File file : allFile) {
				String fileName = file.getName();
				String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
				if (ext == null || ext.trim().length() == 0) {
					continue;
				}
				for (String tmpExt : Constants.TRANSACTION_IMPORT_TEMP_EXT) {
					if (ext.equals(tmpExt)) {
						file.delete();
					}
				}
			}
		}

	}

	public static void main(String[] args) {
		new TransactionUploadServlet()
				.delTempFile("D:\\tmp\\file\\TransactionImportTemp");
	}
}

這裏還有個問題,就是要加入

commons-fileupload

commons-io

這兩個包,我分別用的是commons-fileupload-1.2.2.jar、commons-io-1.4.jar這兩個包,下載地址commons.apache.org ,commons-io這個包雖然沒有在servlet中使用,但是沒有這個包時,上傳會報錯

 

 

上傳顯示進度條,我在調試的時候,沒有細看,好像是通過瀏覽器,查看流量(字節)來算出的百分比,而並不是我想的哪樣,系統不定時的反饋給客戶端數據

 

這些時太忙,有空在去看看

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章