趁着近段的空閑時間,開發任務不是很重,就一直想把以前在倉促時間里所寫的多文件上傳功能改一下,在網上找了很多例子,覺得uploadify還可以,就想用它來試試。實現自己想要的功能。根據官網的開發文檔,同時借鑒別人的經驗,經過斷斷續續的修改(中間一直被安排其它事),把uploadify默認的樣式改,同時把共性都封裝了一下,最終完工了。
1.在_Layout.cshtml 頁面中引入js文件和CSS文件:
1 @*-------上傳文件--------*@ 2 <link href="@Url.Content("~/Scripts/uploadify/css/uploadify.css")" rel="stylesheet" /> 3 <script src="@Url.Content("~/Scripts/JSScript/upload.js")"></script> 4 <script src="@Url.Content("~/Scripts/uploadify/jquery.uploadify.min.js")"></script> 5 <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
2.我把每個頁面都用到的方法封裝在upload.js文件里,同時對各個相關的屬性都作了解釋(最主要的是 'swf': '/Scripts/uploadify/uploadify.swf'這個的路徑要正確):
1 function upload(config) { 2 $("#" + config.id).uploadify({ 3 'method': config.method ? config.method : 'post',//默認是’post’,可以設置為’get’ 4 'formData': config.formData, 5 'swf': '/Scripts/uploadify/uploadify.swf', //關鍵的路徑要正確 6 'uploader': '/HanNeng/Upload', 7 'buttonClass': config.buttonClass ? config.buttonClass : null, //額外增加的上傳按鈕樣式類型 8 'buttonImage': config.buttonImage ? config.buttonImage : null, //按鈕的背景圖片 9 'buttonText': config.buttonText ? config.buttonText : '選擇文件',//按鈕顯示的文字 10 'auto': config.auto ? config.auto : true, //選擇文件后是否自動上傳,默認是true,為自動上傳 11 'height': config.width ? config.width : 25, //按鈕的高度 12 'width': config.width ? config.width : 80, //按鈕的寬度 13 'fileTypeDesc': config.fileTypeDesc, //文件類型的說明 14 'fileTypeExts': config.fileTypeExts, //指定允許上傳的文件類型,默認*.* 15 'fileSizeLimit': config.fileSizeLimit, //上傳文件大小限制,默認單位是KB,若需要限制大小在100KB以內, 可設置該屬性為:‘100KB’ 16 'removeTimeout': 0, //上傳完成后的進度條的顯示時間 17 'queueSizeLimit': config.queueSizeLimit, //上傳隊列長度限制,一次最多可上傳多少個文件 18 'overrideEvents': ['onDialogClose', 'onUploadSuccess', 'onUploadError', 'onSelectError'], //不彈出默認的提示信息 19 'onSWFReady': config.sfdisable == true ? uploadify_onSWFReady : null, //如果有disable參數且為true時,就禁用掉上傳功能 20 'onUploadStart': function (file) { //在一個文件開始上傳之前觸發。 21 $("#" + config.id).uploadify("settings", config.formKey, config.formData); 22 }, 23 'onSelect': uploadify_onSelect, //選擇文件后觸發 24 'onSelectError': uploadify_onSelectError, //選擇文件后出錯時觸發 25 'onUploadError': uploadify_onUploadError,//上傳文件失敗觸發 26 'onUploadSuccess': uploadify_onUploadSuccess //在每一個文件上傳成功后觸發 27 }); 28 } 29 30 //選擇文件錯誤調用的方法 31 var uploadify_onSelectError = function (file, errorCode, errorMsg) { 32 var msgText = "上傳失敗,原因:\n\n"; 33 switch (errorCode) { 34 case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED: 35 msgText += " 每次上傳的文件數量最多只可上傳 " + this.settings.queueSizeLimit + "個文件!\n"; 36 break; 37 case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: 38 msgText += " 文件 【" + file.name + "】 大小超過系統限制的( " + this.settings.fileSizeLimit + " )大小!\n"; 39 break; 40 case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: 41 msgText += " 文件 【" + file.name + "】 大小為0,不可上傳!\n"; 42 break; 43 case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: 44 msgText += " 所選文件 【" + file.name + "】 的格式不正確,僅限上傳(" + this.settings.fileTypeExts + ")的文件格式!\n"; 45 break; 46 default: 47 msgText += "錯誤代碼:" + errorCode + "\n" + errorMsg; 48 } 49 art.dialog.alert(msgText); 50 } 51 52 //文件上傳錯誤調用的方法 53 var uploadify_onUploadError = function (file, errorCode, errorMsg, errorString) { 54 // 手工取消不彈出提示 55 if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED 56 || errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) { 57 return; 58 } 59 var msgText = "上傳失敗\n\n"; 60 switch (errorCode) { 61 case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: 62 msgText += " HTTP 錯誤\n" + errorMsg; 63 break; 64 case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL: 65 msgText += " 上傳文件 【" + file.name + "】 丟失,請重新上傳!\n"; 66 break; 67 case SWFUpload.UPLOAD_ERROR.IO_ERROR: 68 msgText += " IO錯誤!\n"; 69 break; 70 case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: 71 msgText += " 安全性錯誤\n" + errorMsg; 72 break; 73 case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: 74 msgText += " 每次最多上傳 " + this.settings.uploadLimit + "個!\n"; 75 break; 76 case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: 77 msgText += errorMsg; 78 break; 79 case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND: 80 msgText += " 找不到指定文件,請重新操作!\n"; 81 break; 82 case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED: 83 msgText += "參數錯誤!\n"; 84 break; 85 default: 86 msgText += "文件:【" + file.name + "】\n錯誤碼:" + errorCode + "\n" 87 + errorMsg + "\n" + errorString; 88 } 89 art.dialog.alert(msgText); 90 return parameters; 91 } 92 93 //選擇文件調用的方法 94 var uploadify_onSelect = function () { 95 96 } 97 98 //上傳成功后調用的方法 99 var uploadify_onUploadSuccess = function (file, data, response) { 100 var innerHtml = ""; 101 if (response) { 102 var json = (new Function("", "return " + data))(); 103 innerHtml = "<li style=\"list-style: disc\">" 104 + "<a style='color:#C51616' href='/HanNeng/DownFile?filePath=" + json.filePath + "&fileName=" + file.name + "&fileId=" + json.aID + "&backUrl=" + json.backUrl + "&url=" + json.url; 105 if (json.urlID != "0") { 106 innerHtml += "?id=" + json.urlID; 107 } 108 innerHtml += "'>" + file.name + "</a>" + "<a style='margin-left: 10px;' href='javascript:void()' name='deleteImg' curid='" + json.aID + "' onclick=\"DeleteFile(this)\">" 109 + "<img src='/Content/images/delete.png' /></a></li>"; 110 111 //當上傳的文檔為課題的相關文檔時,上傳成功后作特殊處理 112 if (json.attType.indexOf("KT") >= 0) { 113 $.ajax({ 114 type: 'POST', 115 url: '/Subject/SubjectUploadDoc', 116 dataType: 'json', 117 data: { guid: json.guid, atttype: json.attType }, 118 success: function (data) { 119 if (data.isok) { 120 } 121 } 122 }); 123 } 124 } else { 125 innerHtml = "<div>該附件上傳失敗,請重新上傳</div>"; 126 } 127 $("#filename").html($("#filename").html() + innerHtml); 128 } 129 130 //檢測FLASH失敗調用 131 var uploadify_onFallback = function () { 132 art.dialog.alert("您未安裝FLASH控件,無法上傳圖片!請安裝FLASH控件后再試。"); 133 } 134 135 //加載完畢后,禁用uploadify時觸發(通過disable方法) 136 var uploadify_onSWFReady = function () { 137 $('#file_upload').uploadify('disable', true); 138 $(".uploadify-button-text").css("color", "#999"); 139 }
3.MVC里控制器Controller的上傳代碼,並插入數據表中('uploader'這個引用到),在return Json()返回自己想要的參數,之后在上傳成功后,在uploadify_onUploadSuccess方法里獲取傳過來的參數:
1 #region uploadify上傳文件方法 2 [AcceptVerbs(HttpVerbs.Post)] 3 public JsonResult Upload(HttpPostedFileBase fileData) 4 { 5 HanNeng.Common.UpLoadHelper upload = new HanNeng.Common.UpLoadHelper(); 6 string guid = HttpContext.Request.Form["guid"]; 7 string attType = HttpContext.Request.Form["attType"]; 8 string strUrl = HttpContext.Request.Form["url"]; 9 string strUrlID = HttpContext.Request.Form["urlID"]; 10 string backUrl = HttpContext.Request.Form["backUrl"]; 11 int i = 0; 12 int aid = 0; 13 bool istrue = false; 14 if (fileData != null) 15 { 16 try 17 { 18 //文件上傳后的保存路徑 19 string filePath = upload.FilePath;//文件保存的目錄 20 if (!Directory.Exists(filePath)) 21 Directory.CreateDirectory(filePath); //如果不存在UploadFile文件夾,則創建UploadFile文件夾 22 23 upload.FileName = System.IO.Path.GetFileName(fileData.FileName); //得到文件名字 24 upload.FileWithoutName = System.IO.Path.GetFileNameWithoutExtension(fileData.FileName); //不含有擴展名 25 upload.FileSize = fileData.ContentLength; //得到文件大小 26 upload.FileExt = upload.GetExt(fileData.FileName);//得到文件擴展名 27 upload.Category = fileData.ContentType; //得到文件輸出類型 28 upload.FileNewName = upload.GetFileName(upload.FileExt); 29 30 //存入文件 31 fileData.SaveAs(filePath + upload.FileNewName);//保存文件到文件夾中 32 string fileName = Path.GetFileName(fileData.FileName);// 原始文件名稱 33 string fileExtension = Path.GetExtension(fileName); // 文件擴展名 34 35 fileData.SaveAs(filePath + upload.FileNewName); 36 string path = "/UploadFile/" + System.IO.Path.GetFileName(upload.FileNewName); 37 38 Model.Attachment att = new Model.Attachment(); 39 att.AttachmentID = System.Guid.NewGuid().ToString("D"); 40 att.FileName = upload.FileName; 41 att.FileLogicName = upload.FileNewName; 42 att.AttachmentType = attType; 43 att.FID = guid; 44 att.FilePath = path; 45 att.FileSize = upload.FileSize; 46 att.FileExtension = upload.FileExt; 47 att.CreateUserID = Identity.UserID; 48 att.CreateTime = DateTime.Now; 49 att.Category = upload.Category; 50 att.States = 1; 51 att.Summary = (i + 1).ToString(); //排序 52 istrue = new BLL.Attachment().Add(att) > 0; 53 if (istrue) 54 { 55 Model.Attachment matt = new BLL.Attachment().GetModel("AttachmentID", att.AttachmentID); 56 if (matt != null) 57 aid = matt.AttachmentAutoID; 58 } 59 60 return Json(new 61 { 62 Success = true, 63 fileName = att.FileName, 64 SaveName = att.FileLogicName, 65 attType = att.AttachmentType, 66 filePath = att.FilePath, 67 guid = att.FID, 68 aID = aid, 69 url = strUrl, 70 urlID = strUrlID, 71 backUrl = backUrl 72 }, JsonRequestBehavior.AllowGet); 73 } 74 catch (Exception ex) 75 { 76 return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet); 77 } 78 } 79 else 80 return Json(new { Success = false, Message = "請選擇要上傳的文件!" }, JsonRequestBehavior.AllowGet); 81 } 82 #endregion
4.刪除已上傳文件的方法:
1 #region 無刷新刪除上傳的附件 2 public JsonResult DeleteFile(int aID) 3 { 4 bool isOk = false; 5 if (aID > 0) 6 { 7 Model.Attachment att = new BLL.Attachment().GetModel(aID); 8 if (att != null) 9 { 10 isOk = new BLL.Attachment().Delete(aID); 11 //將文件夾里的文件也一起刪除 12 if (System.IO.Directory.Exists(Request.MapPath("~/UploadFile/"))) 13 { 14 if (System.IO.File.Exists(Request.MapPath("~/UploadFile/" + att.FileLogicName))) 15 { 16 System.IO.File.Delete(Request.MapPath("~/UploadFile/" + att.FileLogicName)); 17 } 18 } 19 } 20 } 21 return Json(new { success = isOk }); 22 } 23 #endregion
5.下載文件的方法
1 #region 下載文件-DownFile 2 /// <summary> 3 /// 下載文件 4 /// </summary> 5 /// <param name="filePath">文件路徑</param> 6 /// <param name="fileName">文件名</param> 7 /// <param name="fileId">下載文件自增id</param> 8 /// <param name="url">下載失敗返回界面url</param> 9 /// <returns></returns> 10 public ActionResult DownFile(string filePath, string fileName, string fileId, string url, string backUrl, string r = null) 11 { 12 13 string strurl = ""; 14 if (url != null) 15 strurl = url; 16 if (r != null) 17 strurl = url + "&r=" + r; 18 if (!string.IsNullOrEmpty(backUrl)) 19 { 20 strurl = strurl.Contains("?") ? strurl + "&backUrl=" + Url.Encode(backUrl) : strurl + "?backUrl=" + Url.Encode(backUrl); 21 } 22 if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(fileId)) 23 { 24 return ShowRedirectMessage("下載失敗", url != null ? strurl : "/Student/TableList"); 25 } 26 //絕對路徑 27 filePath = Server.MapPath(filePath); 28 if (!System.IO.File.Exists(filePath)) 29 { 30 new BLL.Attachment().Delete(Convert.ToInt32(fileId)); 31 return ShowRedirectMessage("下載的文件不存在", url != null ? strurl : "/Student/TableList"); 32 } 33 FileStream fs = new FileStream(filePath, FileMode.Open); 34 byte[] bytes = new byte[(int)fs.Length]; 35 fs.Read(bytes, 0, bytes.Length);//讀取文件 36 fs.Close(); 37 Response.Charset = "UTF-8"; 38 Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); 39 Response.ContentType = "application/octet-stream";//以二進制流輸出給瀏覽器 40 //attachment:作為附件下載 inline:直接打開 41 Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileName)); 42 Response.BinaryWrite(bytes); 43 Response.End(); 44 return new EmptyResult(); 45 } 46 #endregion 47 48 #region 獲取附件列表 GetProFile 49 /// <summary> 50 /// 獲取附件列表 51 /// </summary> 52 /// <param name="guid"></param> 53 /// <param name="attType"></param> 54 /// <param name="a"></param> 55 /// <returns></returns> 56 public static List<MvcHtmlString> GetProFile(string guid, string attType, string a = null, string url = null, string backUrl = null) 57 { 58 List<Model.Attachment> M_Att = new BLL.Attachment().GetModelList(guid, attType); 59 List<MvcHtmlString> list = new List<MvcHtmlString>(); 60 string str = ""; 61 foreach (var item in M_Att) 62 { 63 str = "<a style='color:#C51616' href='/HanNeng/DownFile?filePath=" + item.FilePath + "&fileName=" + item.FileName + "&fileId=" + item.AttachmentAutoID + "&url=" + url + "&backUrl=" + backUrl + "'>" + item.FileName + "</a>"; 64 if (a != null) 65 { 66 str += "<a style='margin-left: 10px;' href='javascript:void()' name='deleteImg' curid='" + item.AttachmentAutoID + "' onclick=\"DeleteFile(this)\"><img src='/Content/images/delete.png' /></a>"; 67 } 68 list.Add(new MvcHtmlString(str)); 69 } 70 return list; 71 } 72 #endregion
6.在頁面上的調用,設置一個全局變量var disable = false;是因為有些頁面要根據權限禁用掉上傳的功能。當全部加載完畢調用的是uploadify_onSWFReady方法后,如果disable為true時就禁用,為false時就可上傳:
1 var disable = false; //全局變量 2 //文件上傳 3 function uploadfile() { 4 var config = { 5 id: "file_upload", 6 formKey: "formData", 7 formData: { 'guid': $("#GUID").val(), 'attType': 'XM-PS-101', 'url': '/ProjectInfo/ProjectInfoAdd', 'urlID': $("#ID").val(), 'backUrl': $("#backUrl").val() }, 8 fileTypeDesc: '文件', 9 fileTypeExts: '*.jpg;*.png;*.doc;*.docx;*.xls;*.xlsx;*.pdf', 10 sfdisable: disable 11 }; 12 upload(config); 13 }
1 <input type="button" name="file_upload" id="upload" style="width: 84px; height: 29px;" class="uploadify-button uploadify uploadify-button-text" value="選擇文件" /> 2 3 <input type="file" name="file_upload" id="file_upload" style="display:none"/> 4 <ul id="filename" class="ulfile" style="padding-left: 20px"></ul>
7.最終效果圖:



作者:靜水思寒
出處:http://www.cnblogs.com/jingshuisihan/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
