public void Upload()
{ string imgurl = ""; foreach (string key in Request.Files) { //这里只测试上传第一张图片file[0] HttpPostedFileBase file0 = Request.Files[key]; //转换成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)//图片数据是否为空 { fileFlag = fileByte[0].ToString()+fileByte[1].ToString(); } string[] fileTypeStr = { "255216", "7173", "6677", "13780" };//对应的图片格式jpg,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表单或者上传组件直接访问该方法即可*/ |
|