1. 程式人生 > >.net mvc ajax 上傳檔案

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