C#最齐全的上传图片方法。

时间:2023-03-09 17:50:50
C#最齐全的上传图片方法。
public ActionResult Upload()
        {
            string imgurl = "";
            foreach (string key in Request.Files)
            {
                //这里只测试上传第一张图片file[0]
                HttpPostedFileBase file0 = Request.Files[key];

                //转换成byte,读取图片MIME类型
                Stream stream;
                ; //文件大小KB

                )
                {
                    return Content(ReturnMsg(Enum_Return.失败, "图片不能超过1M:", null));
                }

                ];//contentLength,这里我们只读取文件长度的前两位用于判断就好了,这样速度比较快,剩下的也用不到。
                stream = file0.InputStream;
                stream.Read(fileByte, , );//contentLength,还是取前两位

                //获取图片宽和高
                //System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
                //int width = image.Width;
                //int height = image.Height;

                string fileFlag = "";
                )//图片数据是否为空
                {
                    fileFlag = fileByte[].ToString() + fileByte[].ToString();
                }
                " };//对应的图片格式jpg,gif,bmp,png
                if (fileTypeStr.Contains(fileFlag))
                {
                    string action = Request["action"];
                    string path = "/uploads/";
                    switch (action)
                    {
                        case "headimage":
                            path += "headimage/";
                            break;
                        case "blogtype":
                            path += "blogtype/";
                            break;
                    }
                    string fullpath = 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
                {
                    return Content(ReturnMsg(Enum_Return.失败, "图片格式不正确:"+fileFlag, null));
                }

                stream.Close();
            }

            return Content(ReturnMsg(Enum_Return.成功, "上传成功", imgurl));
        }