標籤:des style blog http io ar color os 使用
參考:http://www.cnblogs.com/luotaoyeah/p/3321070.html
1、下載 uploadify 組件,copy至 Content檔案夾
<link href="~/Content/uploadify/uploadify.css" rel="stylesheet" /><script src="~/Content/uploadify/jquery.uploadify.js"></script>
2、View
<script type="text/javascript">$(function () { $(‘#btn_upload‘).uploadify({ uploader: ‘/home/upload‘, // 伺服器處理地址 swf: ‘/Content/uploadify/uploadify.swf‘, buttonText: "上傳檔案", //按鈕文字 height: 34, //按鈕高度 width: 82, //按鈕寬度 fileTypeExts: "*.jpg;*.png;", //允許的檔案類型 fileTypeDesc: "請選擇圖片檔案", //檔案說明 formData: { "imgType": "normal" }, //提交給伺服器端的參數 onUploadSuccess: function (file, data, response) { //一個檔案上傳成功後的響應事件處理 var data = $.parseJSON(data); $("#photo").attr("src",data.imgpath); //alert(data.imgpath); } });});</script><span id="btn_upload"></span><br /><img id="photo" src="http://www.yxweb.com.cn/images/upphoto.gif" alt="請上傳工作照" />
3、Controller
public ActionResult Upload(HttpPostedFileBase Filedata) { // 沒有檔案上傳,直接返回 if (Filedata == null || string.IsNullOrEmpty(Filedata.FileName) || Filedata.ContentLength == 0) { return HttpNotFound(); } //擷取檔案完整檔案名稱(包含絕對路徑) //檔案存放路徑格式:/files/upload/{日期}/{md5}.{尾碼名} //例如:/files/upload/20130913/43CA215D947F8C1F1DDFCED383C4D706.jpg string fileMD5 = GetStreamMD5(Filedata.InputStream); string FileEextension = Path.GetExtension(Filedata.FileName); string uploadDate = DateTime.Now.ToString("yyyyMMdd"); string imgType = Request["imgType"]; string virtualPath = "/"; if (imgType == "normal") { virtualPath = string.Format("~/files/upload/{0}/{1}{2}", uploadDate, fileMD5, FileEextension); } else { virtualPath = string.Format("~/files/upload2/{0}/{1}{2}", uploadDate, fileMD5, FileEextension); } string fullFileName = this.Server.MapPath(virtualPath); //建立檔案夾,儲存檔案 string path = Path.GetDirectoryName(fullFileName); Directory.CreateDirectory(path); if (!System.IO.File.Exists(fullFileName)) { Filedata.SaveAs(fullFileName); } var data = new { imgtype = imgType, imgpath = virtualPath.Remove(0, 1) }; return Json(data, JsonRequestBehavior.AllowGet); } /// <summary> /// 計算檔案流的md5值 /// </summary> /// <param name="stream">檔案輸入資料流</param> /// <returns></returns> public static String GetStreamMD5(Stream stream) { MD5 md5Hasher = new MD5CryptoServiceProvider(); /*計算指定Stream對象的雜湊值*/ byte[] arrbytHashValue = md5Hasher.ComputeHash(stream); /*由以連字號分隔的十六進位對構成的String,其中每一對錶示value中對應的元素;例如“F-2C-4A”*/ string strHashData = System.BitConverter.ToString(arrbytHashValue).Replace("-", ""); return strHashData; }
【要什麼單車】ASP.NET MVC4筆記02:上傳檔案 uploadify 組件使用