0 ajaxFileUpload簡介
ajaxFileUpload插件是一個很是簡單的基於Jquery的異步上傳文件的插件,使用過程當中發現不少與這個同名的,基於原始版本基礎之上修改過的插件,文件版本比較多,我把我本身使用的ajaxFileUpload文件上傳到博客園上了,想要使用的朋友能夠下載:http://files.cnblogs.com/files/fonour/ajaxfileupload.js。css
整個插件源碼不到200行,實現很是簡單,大體原理就是經過js動態建立隱藏的表單,而後進行提交操做,達到附件上傳的目的,主要實如今源碼裏都有註釋,不難理解,咱們也能夠基於此簡單版本實現更復雜的操做。html
1 ajaxFileUpload使用說明
ajaxFileUpload的使用也很簡單,調用ajaxFileUpload方法便可,各配置項詳細說明以下:java
$.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版本,經測試用各個版本基本沒什麼影響。jquery
<script src="../../Content/js/jquery-2.1.4.min.js"></script> <script src="../../Content/js/ajaxfileupload.js"></script>
頁面添加類型爲file的input標籤ajax
<input type="file" id="filePicture" name="filePicture" accept=".jpg,.jpeg,.png,.bmp" onchange="filePictureChange()" />
經過accept能夠限定打開文件選擇對話框後,默認能選擇的文件類型。文件類型的定義主要有如下這些json
*.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
解決方法:app
經測試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]); } }