Uploadify是JQuery的一個上傳插件,帶進度顯示, 支持多文件上傳。不過官方提供的實例時php版本的
Uploadify唯一的缺點就是不支持中文按鈕
實現
Uploadify實現最低要求:
所需文件
基本代碼
<script type="text/javascript" src="/uploadify/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="/uploadify/swfobject.js"></script> <script type="text/javascript" src="/uploadify/jquery.uploadify.v2.1.4.min.js"></script> <script type="text/javascript"> // <![CDATA[ $(document).ready(function() { $('#file_upload').uploadify({ 'uploader' : '/uploadify/uploadify.swf', 'script' : '/uploadify/uploadify.php', 'cancelImg' : '/uploadify/cancel.png', 'folder' : '/uploads', 'auto' : true }); }); // ]]> </script>
* 確保你有上傳的文件夾的寫入權限.
<input type="file" name="uploadify" id="uploadify" /> <a href="javascript:$('#uploadify').uploadifyUpload()">上傳</a>| <a href="javascript:$('#uploadify').uploadifyClearQueue()">取消上傳</a>
主要參數
示例:
$(document).ready(function() { $('#fileInput1').fileUpload({ 'uploader': 'uploader.swf',//不多講了 'script': '/AjaxByJQuery/file.do',//處理Action 'cancelImg': 'cancel.png', 'folder': '',//服務端默認保存路徑 'scriptData':{'methed':'uploadFile','arg1','value1'}, //向后台傳遞參數,methed,arg1為參數名,uploadFile,value1為對應的參數值,服務端通過request["arg1"] 'buttonText':'UpLoadFile',//按鈕顯示文字,不支持中文,解決方案見下 //'buttonImg':'圖片路徑',//通過設置背景圖片解決中文問題,就是把背景圖做成按鈕的樣子 'multi':'true',//多文件上傳開關 'fileExt':'*.xls;*.csv',//文件過濾器 'fileDesc':'.xls',//文件過濾器 詳解見文檔 'onComplete' : function(event,queueID,file,serverData,data){ //serverData為服務器端返回的字符串值 alert(serverData); } }); });
scriptData
向后台傳遞參數,methed,arg1為參數名,uploadFile,value1為對應的參數值,服務端通過request.getP
onComplete中serverData
后台傳回前台的值
可選參數
uploadify函數的參數為json格式,可以對json對象的key值的修改來進行自定義的設置,如multi設置為true或false來控制是否可以進行多文件上傳,下面就來介紹下這些key值的意思:
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 :選擇文件時觸發,該函數有三個參數
$(document).ready(function() { $("#uploadify").uploadify({ 'uploader': 'JS/jquery.uploadify-v2.1.0/uploadify.swf', 'script': 'UploadHandler.ashx', 'cancelImg': 'JS/jquery.uploadify-v2.1.0/cancel.png', 'folder': 'UploadFile', 'queueID': 'fileQueue', 'auto': false, 'multi': true, 'onInit':function(){alert("1");}, 'onSelect': function(e, queueId, fileObj) { alert("唯一標識:" + queueId + "\r\n" + "文件名:" + fileObj.name + "\r\n" + "文件大小:" + fileObj.size + "\r\n" + "創建時間:" + fileObj.creationDate + "\r\n" + "最后修改時間:" + fileObj.modificationDate + "\r\n" + "文件類型:" + fileObj.type ); } }); });
onSelectOnce :在單文件或多文件上傳時,選擇文件時觸發。該函數有兩個參數event,data,data對象有以下幾個屬性:
onCancel : 當點擊文件隊列中文件的關閉按鈕或點擊取消上傳時觸發。該函數有event、queueId、fileObj、data四個參數,前三個參數同onSelect 中的三個參數,data對象有兩個屬性fileCount和allBytesTotal。
onClearQueue :當調用函數fileUploadClearQueue時觸發。有event和data兩個參數,同onCancel 中的兩個對應參數。
onQueueFull :當設置了queueSizeLimit並且選擇的文件個數超出了queueSizeLimit的值時觸發。該函數有兩個參數event和queueSizeLimit。
onError :當上傳過程中發生錯誤時觸發。該函數有event、queueId、fileObj、errorObj四個參數,其中前三個參數同上,errorObj對象有type和info兩個屬性。
onOpen :點擊上傳時觸發,如果auto設置為true則是選擇文件時觸發,如果有多個文件上傳則遍歷整個文件隊列。該函數有event、queueId、fileObj三個參數,參數的解釋同上。
onProgress :點擊上傳時觸發,如果auto設置為true則是選擇文件時觸發,如果有多個文件上傳則遍歷整個文件隊列,在onOpen之后觸發。該函數有 event、queueId、fileObj、data四個參數,前三個參數的解釋同上。data對象有四個屬性percentage、 bytesLoaded、allBytesLoaded、speed:
onComplete:文件上傳完成后觸發。該函數有四個參數event、queueId、fileObj、response、data五個參數,前三個參數同上。response為后台處理程序返回的值,在上面的例子中為1或0,data有兩個屬性fileCount和speed
$('#file_upload').uploadify({ 'uploader' : '/uploadify/uploadify.swf', 'script' : '/uploadify/uploadify.php', 'cancelImg' : '/uploadify/cancel.png', 'folder' : '/uploads', 'multi' : true, 'onComplete' : function(event, ID, fileObj, response, data) { alert('There are ' + data.fileCount + ' files remaining in the queue.'); } });
注:fileObj對象和上面講到的有些不太一樣,onComplete 的fileObj對象有個filePath屬性可以取出上傳文件的路徑。
onAllComplete:文件隊列中所有的文件上傳完成后觸發。該函數有event和data兩個參數,data有四個屬性,分別為:
$('#file_upload').uploadify({ 'uploader' : '/uploadify/uploadify.swf', 'script' : '/uploadify/uploadify.php', 'cancelImg' : '/uploadify/cancel.png', 'folder' : '/uploads', 'onAllComplete' : function(event,data) { alert(data.filesUploaded + ' files uploaded successfully!'); } });
在上面的例子中已經用了uploadifyUpload和uploadifyClearQueue兩個函數,除此之外還有幾個函數:
uploadifySettings:可以動態修改上面介紹的那些key值,如下面代碼
$('#uploadify').uploadifySettings('folder','JS');
如果上傳按鈕的事件寫成下面這樣,文件將會上傳到uploadifySettings定義的目錄中
<a href="javascript:$('#uploadify').uploadifySettings('folder','JS');
$('#uploadify').uploadifyUpload()">上傳</a>
uploadifyCancel:該函數接受一個queueID作為參數,可以取消文件隊列中指定queueID的文件。
$('#uploadify').uploadifyCancel(id);
常見錯誤:
1.文件大小超了.
<configuration> <system.web> <httpRuntime maxRequestLength="102400" executionTimeout="3600" /> </system.web> </configuration>
2.Session 獲取不到
Flash在IE下會把當前頁面的Cookie發到Upload.ashx,但是Chrome、Firefox下則不會把當前頁面的Cookie發到Upload.ashx。因為Session是靠Cookie中保存的SessionId實現的(傳智播客的ASP.Net視頻教程中講到了Session和Cookie的關系,對於這點不熟悉的可以參考《傳智播客視頻教程2011版:ASP.NET≠拖控件》),這樣由於當前頁面的Cookie不會傳遞給Flash請求的Upload.ashx,因此請求的文件發送到Upload.ashx就是一個新的Session了,當然這個Session就是沒有登錄的了。
解決這個問題的思路也很簡單,那就是手動把SessionId傳遞給服務器,再服務器端讀出SessionId再加載Session。
在Global.asax的Application_BeginRequest中添加如下代碼
#region 上傳組件
void Application_BeginRequest(object sender, EventArgs e)
{
//flash 上傳組件Session 值恢復
//'scriptData': { 'ASPSESSID': '<%=Session.SessionID %>' }
try
{
string session_param_name = "ASPSESSID";
string session_cookie_name = "ASP.NET_SESSIONID";
if (HttpContext.Current.Request.Form[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
}
else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
}
}
catch (Exception ex)
{
//Response.StatusCode = 500;
//Response.Write("Error Initializing Session");
}
//如果網站中還用到了Membership的FormsAuthentication驗證,則還需要把AUTHID也按照SessionID的方法進行處理
//'scriptData': {"ASPSESSID": "<%=Session.SessionID %>","AUTHID" : "<%=Request.Cookies[FormsAuthentication.FormsCookieName].Value%>"}
try
{
string auth_param_name = "AUTHID";
string auth_cookie_name = FormsAuthentication.FormsCookieName;
if (HttpContext.Current.Request.Form[auth_param_name] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
}
else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
}
}
catch (Exception ex)
{
//Response.StatusCode = 500;
//Response.Write("Error Initializing Forms Authentication");
}
}
void UpdateCookie(string cookie_name, string cookie_value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
if (cookie == null)
{
cookie = new HttpCookie(cookie_name);
HttpContext.Current.Request.Cookies.Add(cookie);
}
cookie.Value = cookie_value;
HttpContext.Current.Request.Cookies.Set(cookie);
}
#endregion
#region 上傳組件 void Application_BeginRequest(object sender, EventArgs e) { //flash 上傳組件Session 值恢復 //'scriptData': { 'ASPSESSID': '<%=Session.SessionID %>' } try { string session_param_name = "ASPSESSID"; string session_cookie_name = "ASP.NET_SESSIONID"; if (HttpContext.Current.Request.Form[session_param_name] != null) { UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]); } else if (HttpContext.Current.Request.QueryString[session_param_name] != null) { UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]); } } catch (Exception ex) { //Response.StatusCode = 500; //Response.Write("Error Initializing Session"); } //如果網站中還用到了Membership的FormsAuthentication驗證,則還需要把AUTHID也按照SessionID的方法進行處理 //'scriptData': {"ASPSESSID": "<%=Session.SessionID %>","AUTHID" : "<%=Request.Cookies[FormsAuthentication.FormsCookieName].Value%>"} try { string auth_param_name = "AUTHID"; string auth_cookie_name = FormsAuthentication.FormsCookieName; if (HttpContext.Current.Request.Form[auth_param_name] != null) { UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]); } else if (HttpContext.Current.Request.QueryString[auth_param_name] != null) { UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]); } } catch (Exception ex) { //Response.StatusCode = 500; //Response.Write("Error Initializing Forms Authentication"); } } void UpdateCookie(string cookie_name, string cookie_value) { HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name); if (cookie == null) { cookie = new HttpCookie(cookie_name); HttpContext.Current.Request.Cookies.Add(cookie); } cookie.Value = cookie_value; HttpContext.Current.Request.Cookies.Set(cookie); } #endregion
后端接收代碼
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; HttpPostedFile file = context.Request.Files["Filedata"]; string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]) + "\\"; if (file != null) { if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } file.SaveAs(uploadPath + file.FileName); //下面這句代碼缺少的話,上傳成功后上傳隊列的顯示不會自動消失 context.Response.Write("上傳成功!"); } else { context.Response.Write("0"); } }
源碼下載: Uploadify.zip