.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);
            }
        }

 

posted @ 2019-01-10 12:54  lunawzh  阅读(314)  评论(0编辑  收藏  举报