您好,登錄后才能下訂單哦!
這篇文章主要介紹Asp.net MVC中如何使用JQuery插件ajaxFileUpload上傳文件,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
0 ajaxFileUpload簡介
ajaxFileUpload插件是一個非常簡單的基于Jquery的異步上傳文件的插件,使用過程中發現很多與這個同名的,基于原始版本基礎之上修改過的插件,文件版本比較多,我把我自己使用的ajaxFileUpload文件上傳到博客園上了,想要使用的朋友可以下載:http://xiazai.jb51.net/201611/yuanma/ajaxfileupload(jb51.net).rar。
整個插件源碼不到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]); } }
以上是“Asp.net MVC中如何使用JQuery插件ajaxFileUpload上傳文件”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。