分享

C#后台识别图片格式

 男人要敢担当 2017-05-24
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表单或者上传组件直接访问该方法即可*/

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约