public void Upload()
{ string imgurl = ""; foreach (string key in Request.Files) { //這里只測試上傳第一張圖片file[0] HttpPostedFileBase file0 = Request.Files[key]; //轉(zhuǎn)換成byte,讀取圖片MIME類型 Stream stream; int size = file0.ContentLength / 1024; //文件大小KB if (size > 1024) { //return Json("圖片不能超過1M",JsonRequestBehavior.DenyGet); } byte[] fileByte = new byte[2];//contentLength,這里我們只讀取文件長度的前兩位用于判斷就好了,這樣速度比較快,剩下的也用不到。 stream = file0.InputStream; stream.Read(fileByte, 0, 2);//contentLength,還是取前兩位 //獲取圖片寬和高 //System.Drawing.Image image = System.Drawing.Image.FromStream(stream); //int width = image.Width; //int height = image.Height; string fileFlag = ""; if (fileByte != null || fileByte.Length == 0)//圖片數(shù)據(jù)是否為空 { fileFlag = fileByte[0].ToString()+fileByte[1].ToString(); } string[] fileTypeStr = { "255216", "7173", "6677", "13780" };//對應(yīng)的圖片格式j(luò)pg,gif,bmp,png if (fileTypeStr.Contains(fileFlag)) { string action = Request["action"]; string path = "Views\\FLOW\\"; switch (action) { case "headimage": path = "headimage/"; break; case "blogtype": path = "blogtype/"; break; } string fullpath = path; if (!Directory.Exists(Server.MapPath(fullpath))) { Directory.CreateDirectory(Server.MapPath(fullpath)); } string map = "~/" + fullpath + Request.Files[0].FileName; Request.Files[key].SaveAs(Server.MapPath(map)); imgurl = fullpath + Request.Files[key].FileName; } else { //return Json("圖片格式不正確",JsonRequestBehavior.DenyGet); } stream.Close(); } //return Json("上傳成功", JsonRequestBehavior.DenyGet); } /*前臺:from表單或者上傳組件直接訪問該方法即可*/ |
|