方法里包括了图片大小限制、图片尺寸、文件内容等等的判断。。。
该案例是mvc下的demo,支持单张图片上传。
代码如下 | 复制代码 |
publicActionResult Upload() { stringimgurl =""; foreach(stringkeyinRequest.Files) { //这里只测试上传第一张图片file[0] HttpPostedFileBase file0 = Request.Files[key]; //转换成byte,读取图片MIME类型 Stream stream; intsize = file0.ContentLength / 1024;//文件大小KB if(size > 1024) { returnContent(ReturnMsg(Enum_Return.失败,"图片不能超过1M:",null)); } byte[] fileByte =newbyte[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; stringfileFlag =""; 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)) { stringaction = Request["action"]; stringpath ="/uploads/"; switch(action) { case"headimage": path ="headimage/"; break; case"blogtype": path ="blogtype/"; break; } stringfullpath = path UserInfo.userID "/"; if(!Directory.Exists(Server.MapPath(fullpath))) { Directory.CreateDirectory(Server.MapPath(fullpath)); } Request.Files[key].SaveAs(Server.MapPath(fullpath Request.Files[key].FileName)); imgurl = fullpath Request.Files[key].FileName; } else { returnContent(ReturnMsg(Enum_Return.失败,"图片格式不正确:"fileFlag,null)); } stream.Close(); } returnContent(ReturnMsg(Enum_Return.成功,"上传成功", imgurl)); } |
一般处理程序
代码如下 | 复制代码 |
publicvoidProcessRequest(HttpContext context) { context.Response.ContentType ="application/json"; HttpPostedFile _upfile = context.Request.Files["File"]; if(_upfile.ContentLength < 500000) { if(string.IsNullOrEmpty(_upfile.FileName)) { context.Response.Write("请上传图片"); } stringfileFullname = _upfile.FileName; stringdataName = DateTime.Now.ToString("yyyyMMddhhmmss"); stringfileName = fileFullname.Substring(fileFullname.LastIndexOf("\") 1); stringtype = fileFullname.Substring(fileFullname.LastIndexOf(".") 1); if(type =="bmp"|| type =="jpg"|| type =="gif"|| type =="JPG"|| type =="BMP"|| type =="GIF") { _upfile.SaveAs(HttpContext.Current.Server.MapPath("photo") "\" dataName "." type); HttpCookie cookie =newHttpCookie("photo"); context.Response.Write("上传成功"); } else { context.Response.Write("支持格式:|jpg|gif|bmp|"); } } else { context.Response.Write("你的图片已经超过500K的大小!"); } } |
敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载像素火影骨架佐助 (Perseverance Fire Shadow)手机版v1.16
下载要塞英雄 安卓版v33.20.0-39082670-Android
下载梦想城镇vivo最新版本 安卓版v12.0.1
梦想城镇vivo版是这款卡通风模拟经营类手游的渠道服版本,玩
怦然心动的瞬间 安卓版v1.0
怦然心动的瞬间是一款真人向的恋爱互动游戏,在游戏中玩家将扮演
曼尼汉堡店游戏 安卓版v1.0.3
曼尼汉堡店是一款非常好玩的精品恐怖类型冒险游戏,在这款游戏中
现代总统模拟器去广告版 安卓版v1.0.46
现代总统模拟器是一款休闲养成类游戏,可能对于不少的玩家来说都
现代总统模拟器付费完整版 安卓版v1.0.46
现代总统模拟器高级版在商店是需要付费的,相对于普通版本,高级