標籤:
0 ajaxFileUpload簡介
ajaxFileUpload外掛程式是一個非常簡單的基於Jquery的非同步上傳檔案的外掛程式,使用過程中發現很多與這個同名的,基於原始版本基礎之上修改過的外掛程式,檔案版本比較多,我把我自己使用的ajaxFileUpload檔案上傳到部落格園上了,想要使用的朋友可以下載:http://files.cnblogs.com/files/fonour/ajaxfileupload.js。
整個外掛程式源碼不到200行,實現非常簡單,大致原理就是通過js動態建立隱藏的表單,然後進行提交操作,達到附件上傳的目的,主要實現在源碼裡都有注釋,不難理解,我們也可以基於此簡單版本實現更複雜的操作。
1 ajaxFileUpload使用說明
ajaxFileUpload的使用也很簡單,調用ajaxFileUpload方法即可,各配置項詳細說明如下:
$.ajaxFileUpload({ type: "post", //請求類型:post或get,當要使用data提交自訂參數時一定要設定為post url: "/Shared/Upload", //檔案上傳的伺服器端請求地址 secureuri: false, //是否啟用安全提交,一般預設為false就行,不用特殊處理 fileElementId: "filePicture", //檔案上傳控制項的id <input type="file" id="filePicture" name="filePicture" accept=".jpg,.jpeg,.png,.bmp" onchange="filePictureChange()" /> dataType: "json", //傳回值類型,一般設定為json,還支援html\xml\script類型 data: { "id": "1", "name": "test" }, //用於post請求提交自訂參數 success: function (data, status) { //伺服器成功響應處理函數 }, error: function (data, status, e) { //伺服器響應失敗處理函數 } });
首先在頁面添加對JQuery及ajaxFileUpload的引用,這裡的JQuery用的2.1.4版本,經測試用各個版本基本沒什麼影響。
<script src="../../Content/js/jquery-2.1.4.min.js"></script><script src="../../Content/js/ajaxfileupload.js"></script>
頁面添加類型為file的input標籤
<input type="file" id="filePicture" name="filePicture" accept=".jpg,.jpeg,.png,.bmp" onchange="filePictureChange()" />
通過accept可以限定開啟檔案選擇對話方塊後,預設能選擇的檔案類型。檔案類型的定義主要有以下這些
*.3gpp audio/3gpp, video/3gpp 3GPP Audio/Video*.ac3 audio/ac3 AC3 Audio*.asf allpication/vnd.ms-asf Advanced Streaming Format*.au audio/basic AU Audio*.css text/css Cascading Style Sheets*.csv text/csv Comma Separated Values*.doc application/msword MS Word Document*.dot application/msword MS Word Template*.dtd application/xml-dtd Document Type Definition*.dwg image/vnd.dwg AutoCAD Drawing Database*.dxf image/vnd.dxf AutoCAD Drawing Interchange Format*.gif image/gif Graphic Interchange Format*.htm text/html HyperText Markup Language*.html text/html HyperText Markup Language*.jp2 image/jp2 JPEG-2000*.jpe image/jpeg JPEG*.jpeg image/jpeg JPEG*.jpg image/jpeg JPEG*.js text/javascript, application/javascript JavaScript*.json application/json JavaScript Object Notation*.mp2 audio/mpeg, video/mpeg MPEG Audio/Video Stream, Layer II*.mp3 audio/mpeg MPEG Audio Stream, Layer III*.mp4 audio/mp4, video/mp4 MPEG-4 Audio/Video*.mpeg video/mpeg MPEG Video Stream, Layer II*.mpg video/mpeg MPEG Video Stream, Layer II*.mpp application/vnd.ms-project MS Project Project*.ogg application/ogg, audio/ogg Ogg Vorbis*.pdf application/pdf Portable Document Format*.png image/png Portable Network Graphics*.pot application/vnd.ms-powerpoint MS PowerPoint Template*.pps application/vnd.ms-powerpoint MS PowerPoint Slideshow*.ppt application/vnd.ms-powerpoint MS PowerPoint Presentation*.rtf application/rtf, text/rtf Rich Text Format*.svf image/vnd.svf Simple Vector Format*.tif image/tiff Tagged Image Format File*.tiff image/tiff Tagged Image Format File*.txt text/plain Plain Text*.wdb application/vnd.ms-works MS Works Database*.wps application/vnd.ms-works Works Text Document*.xhtml application/xhtml+xml Extensible HyperText Markup Language*.xlc application/vnd.ms-excel MS Excel Chart*.xlm application/vnd.ms-excel MS Excel Macro*.xls application/vnd.ms-excel MS Excel Spreadsheet*.xlt application/vnd.ms-excel MS Excel Template*.xlw application/vnd.ms-excel MS Excel Workspace*.xml text/xml, application/xml Extensible Markup Language*.zip aplication/zip Compressed Archive
我這裡沒有單獨放上傳按鈕,添加了onchange事件,在選擇檔案後立即上傳檔案,onchange時間定義如下。
function filePictureChange() { $.ajaxFileUpload({ url: "/Shared/Upload", //用於檔案上傳的伺服器端請求地址 type: "post", secureuri: false, //一般設定為false fileElementId: "filePicture", //檔案上傳空間的id屬性 dataType: "json", //傳回值類型 一般設定為json success: function (data, status) { //伺服器成功響應處理函數 alert(data.fileName); alert(data.filePath); alert(data.fileSize); }, error: function (data, status, e){ //伺服器響應失敗處理函數 alert(e); } }); };
後台控制器處理方法如下,使用MD5處理,判斷檔案是否已經存在,避免檔案重複上傳。
/// <summary> /// 附件上傳 /// </summary> /// <returns></returns> public ActionResult Upload() { HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; if (files.Count == 0) return Json("Faild", JsonRequestBehavior.AllowGet); MD5 md5Hasher = new MD5CryptoServiceProvider(); /*計算指定Stream對象的雜湊值*/ byte[] arrbytHashValue = md5Hasher.ComputeHash(files[0].InputStream); /*由以連字號分隔的十六進位對構成的String,其中每一對錶示value中對應的元素;例如“F-2C-4A”*/ string strHashData = System.BitConverter.ToString(arrbytHashValue).Replace("-", ""); string FileEextension = Path.GetExtension(files[0].FileName); string uploadDate = DateTime.Now.ToString("yyyyMMdd"); string virtualPath = string.Format("/Data/ComponentAttachments/{0}/{1}{2}", uploadDate, strHashData, FileEextension); string fullFileName = Server.MapPath(virtualPath); //建立檔案夾,儲存檔案 string path = Path.GetDirectoryName(fullFileName); Directory.CreateDirectory(path); if (!System.IO.File.Exists(fullFileName)) { files[0].SaveAs(fullFileName); } string fileName = files[0].FileName.Substring(files[0].FileName.LastIndexOf("\\") + 1, files[0].FileName.Length - files[0].FileName.LastIndexOf("\\") - 1); string fileSize = GetFileSize(files[0].ContentLength); return Json(new { FileName = fileName, FilePath = virtualPath, FileSize = fileSize }, "text/html", JsonRequestBehavior.AllowGet); } /// <summary> /// 擷取檔案大小 /// </summary> /// <param name="bytes"></param> /// <returns></returns> private string GetFileSize(long bytes) { long kblength = 1024; long mbLength = 1024 * 1024; if (bytes < kblength) return bytes.ToString() + "B"; if (bytes < mbLength) return decimal.Round(decimal.Divide(bytes, kblength), 2).ToString() + "KB"; else return decimal.Round(decimal.Divide(bytes, mbLength), 2).ToString() + "MB"; }2 ajaxFileUpload使用過程中的一些問題2.0 jQuery.handleError is not a function
解決方案:
經測試handlerError只在jquery-1.4.2之前的版本中存在,以後版本中都沒有這個函數了,因此在將handleError這個函數複製到ajaxFileUpload.js中,就行了
uploadHttpData: function (r, type) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if (type == "script") jQuery.globalEval(data); // Get the JavaScript object, if JSON is used. if (type == "json") eval("data = " + data); //eval("data = \"" + data + "\""); // evaluate scripts within html if (type == "html") jQuery("<div>").html(data).evalScripts(); return data; }, handleError: function (s, xhr, status, e) { // If a local callback was specified, fire it if (s.error) { s.error.call(s.context || s, xhr, status, e); } // Fire the global callback if (s.global) { (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]); } }
JQuery檔案上傳外掛程式ajaxFileUpload在Asp.net MVC中的使用