Form提交时,须注意form需要添加属性enctype="multipart/form-data",否则Request.Files.Count=0,无法上传图片。

cshtml代码:

<form id="form1" name="form1" action="SavaeTopicType.aspx" method="post" enctype="multipart/form-data">
</form>

cs代码:

        public bool ValidateImg(string imgName)
        {
            string[] imgType = new string[] { "gif", "jpg", "png", "bmp" };

            int i = 0;
            bool blean = false;
            string message = string.Empty;

            //判断是否为Image类型文件
            while (i < imgType.Length)
            {
                if (imgName.Equals(imgType[i].ToString()))
                {
                    blean = true;
                    break;
                }
                else if (i == (imgType.Length - 1))
                {
                    break;
                }
                else
                {
                    i++;
                }
            }
            return blean;
        }

        public string upLoadImg(string fileName)
        {
            //上传和返回(保存到数据库中)的路径
            string uppath = string.Empty;
            string savepath = string.Empty;
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase imgFile = Request.Files[fileName];
                if (imgFile != null)
                {
                    //创建图片新的名称
                    string nameImg = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    //获得上传图片的路径
                    string strPath = imgFile.FileName;
                    //获得上传图片的类型(后缀名)
                    string type = strPath.Substring(strPath.LastIndexOf(".") + 1).ToLower();
                    if (ValidateImg(type))
                    {
                        //拼写数据库保存的相对路径字符串
                        savepath = "..\\UpImgs\\";
                        savepath += nameImg + "." + type;
                        //拼写上传图片的路径
                        uppath = Server.MapPath("~/UpImgs/");
                        uppath += nameImg + "." + type;
                        //上传图片
                        imgFile.SaveAs(uppath);
                    }
                    return savepath;
                }
            }
            return "";