在HTML中上传图片文件和后台接受处理

在这里我们用到的是 HttpFileCollection类

HTML中代码:

    <form action="/Home/Save" method="post" enctype="multipart/form-data">
        <!--method必须为post enctype必须设置为multipart/form-data否则后台的HttpFileCollection的Count属性为0-->
        <input type="file" name="ImageFile"  />
        <input type="submit"  value="上传" />
    </form>

后台Home控制器中Save方法代码:

 public ActionResult Save()
        {

            HttpRequest request = System.Web.HttpContext.Current.Request;
            HttpFileCollection FileCollect = request.Files;
            if (FileCollect.Count > 0)          //如果集合的数量大于0
            {
                foreach (string str in FileCollect)
                {
                    HttpPostedFile FileSave = FileCollect[str];  //用key获取单个文件对象HttpPostedFile
                    string imgName = DateTime.Now.ToString("yyyyMMddhhmmss");
                    string imgPath = "/" + imgName + FileSave.FileName;     //通过此对象获取文件名
                    string AbsolutePath = Server.MapPath(imgPath);
                    FileSave.SaveAs(AbsolutePath);              //将上传的东西保存
                    Response.Write("<img src='" + imgPath + "'/>");
                }
            }
            return Content("键值对数目:" + FileCollect.Count);

        }

猜你喜欢

转载自blog.csdn.net/weixin_40184249/article/details/80221979
今日推荐