.net mvc ajax 上传文件

1、前端

 <div>
     <input type="file" id="upfile" />
     <button type="button" id="btn"> 上 传 </button>
 </div>
    $("#btn").click(function () {
        var files = document.getElementById("upfile").files;
        if (files.length == 0) {
            alert("请选择文件");
            return;
        }
        var formdata=new FormData();
        formdata.append("file", files[0]);

        $.ajax({
            url: "/home/upload",
            type: "post",
            data: formdata,
            contentType: false,
            processData: false,
            success: function (data) {
                if (data == "ok") {
                    alert("成功");
                } else {
                    alert("失败");
                }
            }
        });
    });

2、后端

        [HttpPost]
        public ActionResult upload(HttpPostedFileBase file)
        {
            try
            {
                var filename = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("/"), filename);
                file.SaveAs(path);
                return Content("ok");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

猜你喜欢

转载自www.cnblogs.com/lunawzh/p/10249342.html