來源:http://www.cnblogs.com/goody9807/archive/2008/11/04/1326098.html
?
功能完全支持ie和firefox瀏覽器!
一般的WEB方式文件上傳只能一個一個的進行上傳,在某些應用上就顯得很不人性化,客戶們都希望能夠1次選擇很多文件,然后讓系統把選擇的文件全部上傳。
這里,就將針對這個問題提出一個比較完美的解決方案,利用的技術主要有2個:Flash 和 smartupload。Flash 能夠讓客戶一次選擇多個文件,而smartupload負責將選擇的文件上傳到服務器上。
有些朋友看到這里,就知道了,其實就是swfupload方法,具體信息可以訪問swfupload官方網站:http://www.swfupload.org/
讓我們先來看看客戶端的界面效果圖。(多選文件,批量上傳,上傳進度顯示)?
要做到圖中的效果,其實很方便,看完下面的描述,相信大家都可以實現上圖中的效果了。
說明:swfupload2中通過一個png圖片與flash插件進行關聯,可以修改images下的png圖片來(如上圖中的[選擇文件]圖片)自定義顯示自己想要的圖片樣子(不要修改圖片名字和格式)。
如果你用的不是java環境,不要緊,只要稍作修改,同樣可以使用在其他的環境中。
第1步,要進行下面的過程,必須先準備好Flash插件和smartupload。
Flash插件:相信大家的瀏覽器早已經安裝過了,請檢查版本,盡量使用最新的的flash插件。
smartupload:大家可以去看看我的另一篇文章 [上傳下載組件SmartUpload使用方法] http://stephen830.javaeye.com/blog/255010 里面詳細講述了使用方法,并且提供了具體java類的下載。請先熟悉smartupload,然后再開始下面的步驟。
第2步,前臺部分準備客戶操作的WEB界面 ,如下[UploadFileExample.jsp、UploadFileExampleSubmit.jsp]
(關于參數 upload_url: "<%=uploadUrl.toString()%>",
要注意提交文件路徑,最好用http://.../UploadFileExample.jsp格式的完整路徑,即像我例子中寫的那樣)
UploadFileExample.jsp
Html代碼
< %@?page?contentType ="text/html;charset=UTF-8" %> ??< % ??????double?perMaxSize ?=?1 .5;//單個文件允許的max大小 ??????String?sizeUnit ?=?"MB" ;//perMaxSize數據對應的單位 ??????String?ext ?=?"*.jpg;*.jpeg;*.gif" ;//允許上傳的文件類型 ??????//文件上傳提交的目標頁面 ??????StringBuffer?uploadUrl ?=?new ?StringBuffer("http://"); ??????uploadUrl.append(request.getHeader("Host")); ??????uploadUrl.append(request.getContextPath()); ??????uploadUrl.append("/admin/swfuploadexample/UploadFileExampleSubmit.jsp"); ??%> ??<!DOCTYPE?HTML?PUBLIC?"-//W3C//DTD?HTML?4.01?Transitional//EN"> ??< html > ??< head > ??< title > 批量相片上傳</ title > ??< meta ?http-equiv ="Content-Type" ?content ="text/html;?charset=UTF-8" > ??< link ?href ="css/default.css" ?rel ="stylesheet" ?type ="text/css" ?/> ??< script ?type ="text/javascript" ?src ="js/swfupload.js" > </ script > ??< script ?type ="text/javascript" ?src ="js/swfupload.swfobject.js" > </ script > ??< script ?type ="text/javascript" ?src ="js/swfupload.queue.js" > </ script > ??< script ?type ="text/javascript" ?src ="js/fileprogress.js" > </ script > ??< script ?type ="text/javascript" ?src ="js/handlers.js" > </ script > ????< script ?type ="text/javascript" > ??var?swfu; ????SWFUpload.onload ?=?function ?()?{ ??????var?settings ?=?{ ??????????flash_url?:?"js/swfupload.swf", ??????????upload_url:?"< %=uploadUrl.toString()%> ", ??????????post_params:?{ ??????????????"user_id"?:?"stephen830", ??????????????"pass_id"?:?"123456" ??????????}, ??????????file_size_limit?:?"< %=perMaxSize%> ?< %=sizeUnit%> ", ??????????file_types?:?"< %=ext%> ", ??????????file_types_description?:?"< %=ext%> ", ??????????file_upload_limit?:?100, ??????????file_queue_limit?:?0, ??????????custom_settings?:?{ ??????????????progressTarget?:?"fsUploadProgress", ??????????????cancelButtonId?:?"btnCancel", ??????????????uploadButtonId?:?"btnUpload", ??????????????myFileListTarget?:?"idFileList" ??????????}, ??????????debug:?false, ??????????auto_upload:false, ????????????//?Button?Settings ??????????button_image_url?:?"images/XPButtonUploadText_61x22.png",???//?Relative?to?the?SWF?file ??????????button_placeholder_id?:?"spanButtonPlaceholder", ??????????button_width:?61, ??????????button_height:?22, ????????????//?The?event?handler?functions?are?defined?in?handlers.js ??????????swfupload_loaded_handler?:?swfUploadLoaded, ??????????file_queued_handler?:?fileQueued, ??????????file_queue_error_handler?:?fileQueueError, ??????????file_dialog_complete_handler?:?fileDialogComplete, ??????????upload_start_handler?:?uploadStart, ??????????upload_progress_handler?:?uploadProgress, ??????????upload_error_handler?:?uploadError, ??????????upload_success_handler?:?uploadSuccess, ??????????upload_complete_handler?:?uploadComplete, ??????????queue_complete_handler?:?queueComplete,?//?Queue?plugin?event ?????????? ??????????//?SWFObject?settings ??????????minimum_flash_version?:?"9.0.28", ??????????swfupload_pre_load_handler?:?swfUploadPreLoad, ??????????swfupload_load_failed_handler?:?swfUploadLoadFailed ??????}; ????????swfu ?=?new ?SWFUpload(settings); ??} ????</ script > ??</ head > ??< body ?bgcolor ="#FCFCFC" ?topmargin ="0px" ?leftmargin ="10px" ?rightmargin ="10px" ?scroll ="yes" > ??< table ?width ="100%" ?cellspacing ="4" ?cellpadding ="4" ?border ="0" ?bgcolor ="#FCFCFC" > ??????< tr > ? ??????< td ?class ="DH1" > ??????< table ?width ="100%" ?cellspacing ="4" ?cellpadding ="4" ?border ="0" ?bgcolor ="#FCFCFC" > ??????< tr > ??????< td ?class ="DH2" > ??????< STRONG > 批量上傳相片?(支持的相片類型:< %=ext%> ;單個相片最大不能超過:< %=perMaxSize%> ?< %=sizeUnit%> )</ STRONG > ? ??????</ td > < td ?class ="DH2" ?align ="right" > </ td > ??????</ tr > ??????</ table > ??< div ?id ="content" > ??????< form ?id ="form1" ?action ="UploadFileExampleSubmit.jsp" ?method ="post" ?enctype ="multipart/form-data" > ??????????< table ?width ="90%" ?cellspacing ="0" ?cellpadding ="0" ?border ="0" > < tr > < td > ??????????< span ?id ="spanButtonPlaceholder" > </ span > ??????????< input ?id ="btnUpload" ?type ="button" ?value ="上傳相片" ?class ="btn" ?/> ??????????< input ?id ="btnCancel" ?type ="button" ?value ="取消全部上傳" ?disabled ="disabled" ?class ="btn" ?/> </ td > ??????????</ tr > </ table > ??????????< table ?id ="idFileList" ?class ="uploadFileList" > < tr ?class ="uploadTitle" > < td > < B > 文件名</ B > </ td > < td > < B > 文件大小</ B > </ td > < td ?width =100px > < B > 狀態</ B > </ td > < td ?width =35px > </ td > </ tr > </ table > ??????????等待上傳?< span ?id ="idFileListCount" > 0</ span > ?個?,成功上傳?< span ?id ="idFileListSuccessUploadCount" > 0</ span > ?個 ??????????< div ?id ="divSWFUploadUI" ?style ="visibility:?hidden;" > </ div > ??????????< noscript ?style ="display:?block;?margin:?10px?25px;?padding:?10px?15px;" > ??????????????很抱歉,相片上傳界面無法載入,請將瀏覽器設置成支持JavaScript。 ??????????</ noscript > ??????????< div ?id ="divLoadingContent" ?class ="content" ?style ="background-color:?#FFFF66;?border-top:?solid?4px?#FF9966;?border-bottom:?solid?4px?#FF9966;?margin:?10px?25px;?padding:?10px?15px;?display:?none;" > ??????????????相片上傳界面正在載入,請稍后... ??????????</ div > ??????????< div ?id ="divLongLoading" ?class ="content" ?style ="background-color:?#FFFF66;?border-top:?solid?4px?#FF9966;?border-bottom:?solid?4px?#FF9966;?margin:?10px?25px;?padding:?10px?15px;?display:?none;" > ??????????????相片上傳界面載入失敗,請確保瀏覽器已經開啟對JavaScript的支持,并且已經安裝可以工作的Flash插件版本。 ??????????</ div > ??????????< div ?id ="divAlternateContent" ?class ="content" ?style ="background-color:?#FFFF66;?border-top:?solid?4px?#FF9966;?border-bottom:?solid?4px?#FF9966;?margin:?10px?25px;?padding:?10px?15px;?display:?none;" > ??????????????很抱歉,相片上傳界面無法載入,請安裝或者升級您的Flash插件。 ??????????????請訪問:?< a ?href ="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" ?target ="_blank" > Adobe網站</ a > ?獲取最新的Flash插件。 ??????????</ div > ??????</ form > ??</ div > ??</ td > </ tr > </ table > ??</ body > ??</ html > ??
<%@ page contentType="text/html;charset=UTF-8"%>
<%
double perMaxSize = 1.5;//單個文件允許的max大小
String sizeUnit = "MB";//perMaxSize數據對應的單位
String ext = "*.jpg;*.jpeg;*.gif";//允許上傳的文件類型
//文件上傳提交的目標頁面
StringBuffer uploadUrl = new StringBuffer("http://");
uploadUrl.append(request.getHeader("Host"));
uploadUrl.append(request.getContextPath());
uploadUrl.append("/admin/swfuploadexample/UploadFileExampleSubmit.jsp");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>批量相片上傳</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="css/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/swfupload.js"></script>
<script type="text/javascript" src="js/swfupload.swfobject.js"></script>
<script type="text/javascript" src="js/swfupload.queue.js"></script>
<script type="text/javascript" src="js/fileprogress.js"></script>
<script type="text/javascript" src="js/handlers.js"></script>
<script type="text/javascript">
var swfu;
SWFUpload.onload = function () {
var settings = {
flash_url : "js/swfupload.swf",
upload_url: "<%=uploadUrl.toString()%>",
post_params: {
"user_id" : "stephen830",
"pass_id" : "123456"
},
file_size_limit : "<%=perMaxSize%> <%=sizeUnit%>",
file_types : "<%=ext%>",
file_types_description : "<%=ext%>",
file_upload_limit : 100,
file_queue_limit : 0,
custom_settings : {
progressTarget : "fsUploadProgress",
cancelButtonId : "btnCancel",
uploadButtonId : "btnUpload",
myFileListTarget : "idFileList"
},
debug: false,
auto_upload:false,
// Button Settings
button_image_url : "images/XPButtonUploadText_61x22.png", // Relative to the SWF file
button_placeholder_id : "spanButtonPlaceholder",
button_width: 61,
button_height: 22,
// The event handler functions are defined in handlers.js
swfupload_loaded_handler : swfUploadLoaded,
file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_start_handler : uploadStart,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
queue_complete_handler : queueComplete, // Queue plugin event
// SWFObject settings
minimum_flash_version : "9.0.28",
swfupload_pre_load_handler : swfUploadPreLoad,
swfupload_load_failed_handler : swfUploadLoadFailed
};
swfu = new SWFUpload(settings);
}
</script>
</head>
<body bgcolor="#FCFCFC" topmargin="0px" leftmargin="10px" rightmargin="10px" scroll="yes">
<table width="100%" cellspacing="4" cellpadding="4" border="0" bgcolor="#FCFCFC">
<tr>
<td class="DH1">
<table width="100%" cellspacing="4" cellpadding="4" border="0" bgcolor="#FCFCFC">
<tr>
<td class="DH2">
<STRONG>批量上傳相片 (支持的相片類型:<%=ext%>;單個相片最大不能超過:<%=perMaxSize%> <%=sizeUnit%>)</STRONG>
</td><td class="DH2" align="right"></td>
</tr>
</table>
<div id="content">
<form id="form1" action="UploadFileExampleSubmit.jsp" method="post" enctype="multipart/form-data">
<table width="90%" cellspacing="0" cellpadding="0" border="0"><tr><td>
<span id="spanButtonPlaceholder"></span>
<input id="btnUpload" type="button" value="上傳相片" class="btn" />
<input id="btnCancel" type="button" value="取消全部上傳" disabled="disabled" class="btn" /></td>
</tr></table>
<table id="idFileList" class="uploadFileList"><tr class="uploadTitle"><td><B>文件名</B></td><td><B>文件大小</B></td><td width=100px><B>狀態</B></td><td width=35px> </td></tr></table>
等待上傳 <span id="idFileListCount">0</span> 個 ,成功上傳 <span id="idFileListSuccessUploadCount">0</span> 個
<div id="divSWFUploadUI" style="visibility: hidden;"></div>
<noscript style="display: block; margin: 10px 25px; padding: 10px 15px;">
很抱歉,相片上傳界面無法載入,請將瀏覽器設置成支持JavaScript。
</noscript>
<div id="divLoadingContent" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
相片上傳界面正在載入,請稍后...
</div>
<div id="divLongLoading" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
相片上傳界面載入失敗,請確保瀏覽器已經開啟對JavaScript的支持,并且已經安裝可以工作的Flash插件版本。
</div>
<div id="divAlternateContent" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
很抱歉,相片上傳界面無法載入,請安裝或者升級您的Flash插件。
請訪問: <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank">Adobe網站</a> 獲取最新的Flash插件。
</div>
</form>
</div>
</td></tr></table>
</body>
</html>
UploadFileExample.jsp對應的處理頁面 --> UploadFileExampleSubmit.jsp
(1)請確保已經看完我的另一篇文章(上傳下載組件SmartUpload使用方法 http://stephen830.javaeye.com/admin/blogs/255010 ),先搞好這個才能開始下面的操作
(2)寫一個對應上傳方法類,com.soft4j.bo.PhotoMgr.java,其中的方法就是文章下面提到的public static String fileUpload(SmartUpload su,PageContext pageContext) throws Exception {...}
這2點弄好了,ok,可以繼續。(如果沒有準備java文件,下面的UploadFileExampleSubmit.jsp會報錯)
注意在(UploadFileExampleSubmit.jsp)中:上傳成功后必須返回“successed”,失敗的話則返回失敗的原因。
Html代碼
< %@?page?contentType ="text/html;charset=UTF-8" %> < %@?page?import ="com.soft4j.httpupload4j.SmartUpload" %> < %@?page?import ="com.soft4j.bo.PhotoMgr" %> < % ??????String?pageErrorInfo ?=?null ; ??????SmartUpload?su ?=?null ; ??????try{ ??????????su ?=?new ?SmartUpload(); ??????????su.initialize(pageContext); ??????????su.upload(); ??????????pageErrorInfo ?=?PhotoMgr .fileUpload(su,pageContext); ??????????if(pageErrorInfo ==null){ ??????????????out.print("successed"); ??????????} ??????}catch(Exception?e){ ??????????pageErrorInfo ?=?e.getMessage(); ??????}finally{ ??????????su ?=?null ; ??????????if(pageErrorInfo!=null){ ??????????????out.print(pageErrorInfo); ??????????} ??????} ??%> ??
<%@ page contentType="text/html;charset=UTF-8"%><%@ page import="com.soft4j.httpupload4j.SmartUpload"%><%@ page import="com.soft4j.bo.PhotoMgr"%><%
String pageErrorInfo = null;
SmartUpload su = null;
try{
su = new SmartUpload();
su.initialize(pageContext);
su.upload();
pageErrorInfo = PhotoMgr.fileUpload(su,pageContext);
if(pageErrorInfo==null){
out.print("successed");
}
}catch(Exception e){
pageErrorInfo = e.getMessage();
}finally{
su = null;
if(pageErrorInfo!=null){
out.print(pageErrorInfo);
}
}
%>
第3步 準備后臺的文件上傳功能。 也就是上面文件[UploadFileExampleSubmit.jsp]中用到的[PhotoMgr.fileUpload(su,pageContext)]方法。
Java代碼
? ? ? ? ? ? ??????public ?static ?String?fileUpload(SmartUpload?su,PageContext?pageContext)?throws ?Exception?{ ??????????com.soft4j.httpupload4j.File?suFile?=?null ; ??????????int ?fileCount?=?0 ; ??????????try ?{ ?????????????? ??????????????String?userId?=?su.getRequest().getParameter("user_id" ); ??????????????String?passId?=?su.getRequest().getParameter("pass_id" ); ????????????????String?fileExt?=?"" ; ??????????????int ?fileSize?=?0 ; ??????????????String?AllowedExtensions?=?",jpg,jpeg,gif," ; ??????????????double ?maxFileSize?=?1.5 *1024 ; ?????????????? ??????????????for ?(int ?i=0 ;?i<su.getFiles().getCount();i++)?{ ??????????????????suFile?=?su.getFiles().getFile(i); ??????????????????if ?(suFile.isMissing()) ??????????????????????continue ; ?????????????????? ??????????????????fileSize?=?suFile.getSize()/1024 ; ??????????????????if (fileSize==0 )?fileSize=1 ; ??????????????????if (maxFileSize<fileSize)?throw ?new ?Exception("單個上傳相片的容量不能超過[" +maxFileSize+"KB]" ); ?????? ?????????????????? ??????????????????if ?(suFile.getFileExt()?==?null ??????????????????????????||?"" .equals(suFile.getFileExt()))?{ ??????????????????????fileExt?=?",," ; ??????????????????}?else ?{ ??????????????????????fileExt?=?"," ?+?suFile.getFileExt().toLowerCase()?+?"," ; ??????????????????} ??????????????????if ?(!"" .equals(AllowedExtensions) ??????????????????????????&&?AllowedExtensions.indexOf(fileExt)?==?-1 )?{ ??????????????????????throw ?new ?Exception("您上傳的文件[" ?+?suFile.getFileName() ??????????????????????????????+?"]的類型為系統禁止上傳的文件類型,不能上傳!" ); ??????????????????} ??????????????????fileCount++; ??????????????} ??????????????if ?(fileCount==0 )?throw ?new ?Exception("請選擇上傳的文件" ); ?????????????? ??????????????String?filePath="D://tomcat//webapps//test//photo//" ; ??????????????for ?(int ?i=0 ;?i<su.getFiles().getCount();i++)?{ ??????????????????suFile?=?su.getFiles().getFile(i); ??????????????????suFile.saveAs(filePath+suFile.getFileName(),SmartUpload.SAVE_PHYSICAL); ??????????????} ?????????????? ??????????????return ?null ; ??????????}?finally ?{ ?????????????? ??????????} ??????}??
/**
* 文件上傳方法.
* @param su
* @param pageContext
* @return
* @throws Exception
*/
public static String fileUpload(SmartUpload su,PageContext pageContext) throws Exception {
com.soft4j.httpupload4j.File suFile = null;
int fileCount = 0;
try {
//獲取傳遞過來的參數
String userId = su.getRequest().getParameter("user_id");
String passId = su.getRequest().getParameter("pass_id");
String fileExt = "";
int fileSize = 0;
String AllowedExtensions = ",jpg,jpeg,gif,";//允許上傳的文件類型
double maxFileSize = 1.5*1024;//單文件最大大小,單位KB
//校驗文件類型和大小
for (int i=0; i<su.getFiles().getCount();i++) {
suFile = su.getFiles().getFile(i);
if (suFile.isMissing())
continue;
//校驗文件大小
fileSize = suFile.getSize()/1024;//字節轉換成KB
if(fileSize==0) fileSize=1;
if(maxFileSize<fileSize) throw new Exception("單個上傳相片的容量不能超過["+maxFileSize+"KB]");
//校驗文件類型
if (suFile.getFileExt() == null
|| "".equals(suFile.getFileExt())) {
fileExt = ",,";
} else {
fileExt = "," + suFile.getFileExt().toLowerCase() + ",";
}
if (!"".equals(AllowedExtensions)
&& AllowedExtensions.indexOf(fileExt) == -1) {
throw new Exception("您上傳的文件[" + suFile.getFileName()
+ "]的類型為系統禁止上傳的文件類型,不能上傳!");
}
fileCount++;
}
if (fileCount==0) throw new Exception("請選擇上傳的文件");
//準備保存文件
String filePath="D://tomcat//webapps//test//photo//";//這里填寫項目中存放上傳文件的物理路徑
for (int i=0; i<su.getFiles().getCount();i++) {
suFile = su.getFiles().getFile(i);
suFile.saveAs(filePath+suFile.getFileName(),SmartUpload.SAVE_PHYSICAL);//保存文件
}
//成功返回null
return null;
} finally {
//
}
}
備注:關于jsp頁面和java方法我不做過多的說明了,應該已經比較清楚了。
附錄:swfupload 文件批量上傳壓縮包 swfupload.zip(支持最新的flash10插件) (附件中沒有java類,請自己準備1個java類,將上面的方法復制進去)
下載:
http://stephen830.javaeye.com/topics/download/58bc72da-1c10-341f-ae10-2d27b74f64bc
總結
以上是生活随笔為你收集整理的step-by-step多文件WEB批量上传(swfupload)的完美解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。