1、jquery.uploadify簡(jiǎn)介
在ASP.NET中上傳的控件有很多,比如.NET自帶的FileUpload,以及SWFUpload,Uploadify等等,尤其后面兩個(gè)控件的用戶體驗(yàn)比較好,無刷新,帶上傳進(jìn)度等等。在最近的短信平臺(tái)開發(fā)中,使用Uploadify進(jìn)行文件上傳。
Uploadify官網(wǎng)地址是:http://www.uploadify.com/ 可滿足項(xiàng)目開發(fā)需求。
下載地址:http://www.uploadify.com/wp-content/uploads/files/uploadify.zip 版本信息如下:
解壓之后,目錄結(jié)構(gòu)如下(不在詳細(xì)解釋):
2、使用流程
下載的程序是PHP示例,由于項(xiàng)目使用的是asp.net mvc,使用uploadify可分以下步驟:
•(1)加入uploadify js類庫(kù)(把uploadify相關(guān)js類庫(kù)引用到項(xiàng)目的相關(guān)位置,比如放到scripts目錄)
•(2)對(duì)uploadify二次進(jìn)行封裝,滿足項(xiàng)目調(diào)用
•(3)編寫文件上傳處理方法
•(4)頁面引用相關(guān)類庫(kù)并編寫上傳腳本
2.1 對(duì)uploadify二次進(jìn)行封裝
針對(duì)uploadify調(diào)用進(jìn)行js類庫(kù)封裝,滿足項(xiàng)目使用:
//轉(zhuǎn)換成key=value&key=value格式 tx.toParam = function (dto) { return jQuery.param(dto); } //設(shè)置上傳文件 tx.uploadify = function (divId, options, action) { if (options == undefined && action == undefined) { $('#' + divId).uploadify("upload"); return; } if (options == undefined) { abp.message.warn("請(qǐng)輸入?yún)?shù)配置"); return; } var fileexts = options.fileexts; if (fileexts == undefined || fileexts.length <= 0) { abp.message.warn("要選擇文件的擴(kuò)展名不能為空"); return; } $('#' + divId).uploadify({ uploader: '/files/upload?r=' + Math.random() + "&fileexts=" + encodeURIComponent(fileexts) + "&" + (options !== undefined ? tx.toParam(options.params) : ""), // 服務(wù)器端處理地址 swf: '/Scripts/uploadify/uploadify.swf', // 上傳使用的 Flash width: 60, // 按鈕的寬度 height: 23, // 按鈕的高度 buttonText: "選擇文件", // 按鈕上的文字 buttonCursor: 'hand', // 按鈕的鼠標(biāo)圖標(biāo) fileObjName: 'Filedata', // 上傳參數(shù)名稱 fileTypeExts: fileexts, // 擴(kuò)展名 fileTypeDesc: "請(qǐng)選擇文件", // 文件說明 fileDesc: '不超過200M的', sizeLimit: 204800000, //允許上傳的文件大小(kb) 此為2M auto: false, // 選擇之后,自動(dòng)開始上傳 multi: true, // 是否支持同時(shí)上傳多個(gè)文件 queueSizeLimit: 1, // 允許多文件上傳的時(shí)候,同時(shí)上傳文件的個(gè)數(shù) onSelectOnce: function (event, data) { //在單文件或多文件上傳時(shí),選擇文件時(shí)觸發(fā) //event 事件對(duì)象(the event object) //data 選擇的操作信息 //data.filesSelected 選擇文件操作中選中的文件數(shù)量 }, onUploadStart: function (file) { //file:將要上載的文件對(duì)象 ShowBusy(); }, onUploadComplete: function (file) { //file:上傳或返回一個(gè)錯(cuò)誤的文件對(duì)象。 }, onUploadSuccess: function (file, data, response) { //file:成功上傳的文件對(duì)象 //data:服務(wù)器端腳本返回的數(shù)據(jù)(任何由文件響應(yīng)的任何東西) //response:服務(wù)器返回的響應(yīng)是否真的成功或錯(cuò)誤,如果沒有響應(yīng)。如果返回false,這successtimeout期權(quán)到期后的反應(yīng)真是假設(shè)。 if (action !== undefined) { action(JSON.parse(data)); } ClearBusy(); }, onUploadError: function (file, errorCode, errorMsg, errorString) { //file:上傳的文件對(duì)象 //errorCode:返回的錯(cuò)誤代碼 //errorMsg:返回的錯(cuò)誤消息 //errorString:包含錯(cuò)誤的所有細(xì)節(jié)的可讀的錯(cuò)誤信息 if (action !== undefined) { if (action !== undefined) { action({ result: errorCode, message: errorMsg, filename: "", fileext: "" }); } } ClearBusy(); } }); }
2.2 文件上傳處理
使用MVC特性,要登錄之后才能進(jìn)行文件上傳:
using System; using System.IO; using System.Security.Principal; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace TxSms.Web.Controllers { /// <summary> /// 文件上傳管理 /// </summary> [Authorize] public class FilesController : TxSmsControllerBase { private static string jsonResult = "{0}"result":{1},"message":"{2}","filename":"{3}","fileext":"{4}"{5}"; /// <summary> /// 文件上傳頁面 /// </summary> /// <returns></returns> [Authorize] public ActionResult Index() { return View(); } /// <summary> /// 上傳文件 /// </summary> /// <param name="filedata"></param> /// <returns></returns> [Authorize] public ActionResult Upload(HttpPostedFileBase filedata) { // 如果沒有上傳文件 if (filedata == null || filedata.FileName.IsNullOrEmpty() || filedata.ContentLength == 0) { return new JsonStringResult(string.Format(jsonResult, "{", -1, "", "", "", "}")); } string parmPath = Request.QueryString["path"]; string parmGetzipfile = Request.QueryString["getzipfile"]; if (parmGetzipfile.IsNullOrEmpty()) { parmGetzipfile = "0"; } // 保存到 ~/uploads 文件夾中,名稱不變 string time = DateTime.Now.ToString("yyyyMMddHHmmssfff"); string fileext = Path.GetExtension(filedata.FileName); string filename = time + fileext; string virtualPath = parmPath.IsNullOrEmpty() ? $"~/uploads/" : $"~/uploads/{parmPath}/"; string actualPath = Server.MapPath(virtualPath); if (!Directory.Exists(actualPath)) { Directory.CreateDirectory(Server.MapPath(virtualPath)); } // 文件系統(tǒng)不能使用虛擬路徑 var destFile = virtualPath + filename; string path = Server.MapPath(destFile); filedata.SaveAs(path); bool iszip = fileext != null && (fileext.Equals(".zip", StringComparison.OrdinalIgnoreCase) && parmGetzipfile.Equals("1")); if (iszip) { var virtualPathZip = virtualPath + time + "/"; string actualPathZip = Server.MapPath(virtualPathZip); if (!Directory.Exists(actualPathZip)) { Directory.CreateDirectory(actualPathZip); } destFile = fileext = ""; //第一步驟,解壓 TxSmsZipHelper.UnZipFile(path, actualPathZip); //第二步驟,獲取excel文件,如果沒有獲取到,則拋出異常 //獲得目錄信息 var dir = new DirectoryInfo(actualPathZip); //獲得目錄文件列表 var files = dir.GetFiles(); foreach (FileInfo fileName in files) { //var ext = Path.GetExtension(fileName.Name).ToLower(); //if (ext == ".xls" || ext == ".xlsx") //{ // destFile = Path.Combine(fileName.DirectoryName, fileName.Name); // break; //} destFile = virtualPathZip + fileName.Name; fileext = Path.GetExtension(fileName.Name); break; } } return new JsonStringResult(string.Format(jsonResult, "{", 0, "上傳成功", destFile, fileext.ToLower(), "}")); } public class JsonStringResult : ContentResult { public JsonStringResult(string json) { Content = json; ContentType = "application/json"; } } } }
文件上傳路徑:/files/upload
2.3 頁面調(diào)用
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <link rel="stylesheet"/> <script src="http://www.gimoo.net/Scripts/jquery-2.1.4.min.js"></script> <script src="http://www.gimoo.net/Scripts/uploadify/jquery.uploadify.min.js"></script> <script type="text/javascript"> $(function () { var ASPSESSID = '3iupfg2udk4m5hyzfj5ydlso'; var auth = ''; //初始化 tx.uploadify('uploadify' , { //參數(shù)配置 fileexts: "*.jpg;*.png;*.zip", //要選擇文件的擴(kuò)展名,多個(gè)用;分割 //formData: { ASPSESSID: ASPSESSID, AUTHID: auth }, params: { //參數(shù) path: 'files',//上傳路徑,允許為空 getzipfile: 1 //解壓zip文件,并獲取文件 0:不解壓獲取,1:解壓獲取 } } , function (data) { //回調(diào)函數(shù) //data.result:0 表示成功,其他表示錯(cuò)誤 //data.message:信息 //data.filename:文件名稱 //data.fileext:文件擴(kuò)展 console.log(data.result); console.log(data.message); console.log(data.filename); console.log(data.fileext); }); $("#btnUpload").click(function () { tx.uploadify('uploadify'); //開始上傳 }); }); </script> </head> <body> <div style="margin: 40px;"> <div id="uploadify"></div> <button id="btnUpload">開始上傳</button> </div> </body> </html>
允許程序,界面如下:
選擇文件—>開始上傳:
ok,到此已經(jīng)完成。
3、http 302解決方案
很懷疑二八原則,很快就出現(xiàn)了。同事用firefox進(jìn)行測(cè)試,遇到如下提示:
查找大量資料,發(fā)下是Upload方法認(rèn)證的問題,去掉[Authorize]屬性標(biāo)簽即可,代碼修改如下:
using System; using System.IO; using System.Web; using System.Web.Mvc; namespace TxSms.Web.Controllers { /// <summary> /// 文件上傳管理 /// </summary> //[Authorize] public class FilesController : TxSmsControllerBase { private static string jsonResult = "{0}"result":{1},"message":"{2}","filename":"{3}","fileext":"{4}"{5}"; /// <summary> /// 文件上傳頁面 /// </summary> /// <returns></returns> [Authorize] public ActionResult Index() { return View(); } /// <summary> /// 上傳文件 /// </summary> /// <param name="filedata"></param> /// <returns></returns> //[Authorize] public ActionResult Upload(HttpPostedFileBase filedata) { //加入認(rèn)證信息 if (this.LoginUser == null) { return new JsonStringResult(string.Format(jsonResult, "{", -1, "抱歉,未登錄,不允許上傳", "", "", "}")); } // 如果沒有上傳文件 if (filedata == null || filedata.FileName.IsNullOrEmpty() || filedata.ContentLength == 0) { return new JsonStringResult(string.Format(jsonResult, "{", -2, "無上傳文件", "", "", "}")); } string parmPath = Request.QueryString["path"]; string parmGetzipfile = Request.QueryString["getzipfile"]; if (parmGetzipfile.IsNullOrEmpty()) { parmGetzipfile = "0"; } // 保存到 ~/uploads 文件夾中,名稱不變 string time = DateTime.Now.ToString("yyyyMMddHHmmssfff"); string fileext = Path.GetExtension(filedata.FileName); string filename = time + fileext; string virtualPath = parmPath.IsNullOrEmpty() ? $"~/uploads/" : $"~/uploads/{parmPath}/"; string actualPath = Server.MapPath(virtualPath); if (!Directory.Exists(actualPath)) { Directory.CreateDirectory(Server.MapPath(virtualPath)); } // 文件系統(tǒng)不能使用虛擬路徑 var destFile = virtualPath + filename; string path = Server.MapPath(destFile); filedata.SaveAs(path); bool iszip = fileext != null && (fileext.Equals(".zip", StringComparison.OrdinalIgnoreCase) && parmGetzipfile.Equals("1")); if (iszip) { var virtualPathZip = virtualPath + time + "/"; string actualPathZip = Server.MapPath(virtualPathZip); if (!Directory.Exists(actualPathZip)) { Directory.CreateDirectory(actualPathZip); } destFile = fileext = ""; //第一步驟,解壓 TxSmsZipHelper.UnZipFile(path, actualPathZip); //第二步驟,獲取excel文件,如果沒有獲取到,則拋出異常 //獲得目錄信息 var dir = new DirectoryInfo(actualPathZip); //獲得目錄文件列表 var files = dir.GetFiles(); foreach (FileInfo fileName in files) { //var ext = Path.GetExtension(fileName.Name).ToLower(); //if (ext == ".xls" || ext == ".xlsx") //{ // destFile = Path.Combine(fileName.DirectoryName, fileName.Name); // break; //} destFile = virtualPathZip + fileName.Name; fileext = Path.GetExtension(fileName.Name); break; } } return new JsonStringResult(string.Format(jsonResult, "{", 0, "上傳成功", destFile, fileext.ToLower(), "}")); } public class JsonStringResult : ContentResult { public JsonStringResult(string json) { Content = json; ContentType = "application/json"; } } } }
再次用firefox測(cè)試如下:
4、注意事項(xiàng)
1、封裝的js類庫(kù)適合單文件上傳
2、upload里面的登錄認(rèn)證是通過判斷當(dāng)前賬號(hào)信息是否為null
3、本項(xiàng)目使用的abp框架,有興趣的可以去了解下:http://www.aspnetboilerplate.com/
以上所述是小編給大家介紹的jQuery.uploadify文件上傳組件實(shí)例講解,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)綠夏網(wǎng)網(wǎng)站的支持!