在.net MVC中异步上传图片或者文件

  @using (Ajax.BeginForm("AddMessages", "MenuInfo", new AjaxOptions { HttpMethod = "post", OnSuccess = "Successd" }, new { @id = "from1", enctype = "multipart/form-data" }))  //这里最好还是加上 enctype = "multipart/form-data" }
            {
        <input  id="IconUrl" name="IconUrl"  >

        <input type="file" id="files" name="files" value="点击选择图片" /> 
          }

JS代码 

   function fileUp() {
            $("#files").change(function () {
                if ($(this).val()) {//选择了图片上传的时候,异步提交
                    $("#from1").ajaxSubmit({  
                        type: "Post",/*设置表单以post方法提交*/
                        dataType: "text", /*设置返回值类型为文本*/
                        url: '/MenuInfo/UploadImage', /*设置post提交到的页面*/
                        success: function (data) {
                            $("#IconUrl").val(data); //把返回来的地址赋到那个input上
                            $("#files").val("");//把值去掉
                        }    })   }   })  } 

后台代码
      public ActionResult UploadImage() {
            if (Request.Files["files"] != null)//判断是否能接收到上传的图片
            {
                var imgurl = Request.Files["files"];//得到上传图片
                string fileEx = Path.GetExtension(imgurl.FileName);
                if (fileEx == ".jpg" || fileEx == ".jpeg")
                { //这储存这个类型 
                    string imagePath = "/Upload/Images/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
                    if (!Directory.Exists(imagePath))
                    {//判断是否有这个文件夹没有创建一个
                        Directory.CreateDirectory(Server.MapPath(imagePath));
                    }
                    //写好保存路径存放
                    string fileName = imagePath + Guid.NewGuid().ToString() + imgurl.FileName;
                    imgurl.SaveAs(Server.MapPath(fileName));
                    return Content(fileName);
                }
                return Content("只支持保存.jpg或者.jpeg格式的图片");
            }
            else {
                 return Content("保存失败");
            }   }
原文地址:https://www.cnblogs.com/zhangzhixiong/p/4267334.html