2016-01-25 37 views
0

我想通过ajax做一个ASP.NET文件上传。我在这个地方Ajax调用:ASP.NET通过ajax上传文件每次都会返回错误

$.ajax({ 
              type: "POST", 
              url: '/Home/Upload', 
              data: formData, 
              dataType: 'json', 
              contentType: false, 
              processData: false, 
              success: function (response) { 
               alert('success!!'); 
               $("#" + id).attr('disabled', false); 
              }, 
              error: function (error) { 
               alert("errror"); 
              } 
             }); 

,这是我的.NET代码:

[HttpPost] 
     public void Upload() 
     { 
      for (int i = 0; i < Request.Files.Count; i++) 
      { 
       var file = Request.Files[i]; 

       string path = Path.Combine(Server.MapPath("~/UploadedFiles"), 
               Path.GetFileName(file.FileName)); 

       file.SaveAs(path); 
      } 

     } 

当我转到该文件夹​​,我可以看到它被上传,但由于某种原因,AJAX回报警报错误,请帮助。

+0

你需要用[HttpPost]一起定义了[WebMethod]属性。 – DinoMyte

回答

1

因为你必须返回一些东西。不用返回它总是给出错误。

[HttpPost] 

    public ActionResult AsyncUpload() 
    { 

     for (int i = 0; i < Request.Files.Count; i++) 
     { 
      var file = Request.Files[i]; 

      string path = Path.Combine(Server.MapPath("~/UploadedFiles"), 
              Path.GetFileName(file.FileName)); 

      file.SaveAs(path); 
     } 

     return Json(new { success = true }, 
      "text/plain"); 
    } 
+0

yay boy!这工作,谢谢! – user979331

+0

然后,我期待一个正确的点击:) –

0

您应该从服务器返回一个布尔值到客户端,以了解过程是否正确完成。

C#:

[HttpPost] 
public void Upload() { 
    try { 
     for (int i = 0; i < Request.Files.Count; i++) { 
      // your stuff 
     } 
     return true; 
    } catch (Exception) { 
     return false; 
    } 
} 

** JS:**

$.ajax({ 
    // your options 
    success: function (response) { 
     if (response) { 
      alert('success!!'); 
      $("#" + id).attr('disabled', false); 
     } else { 
      alert("an errror occurred"); 
     } 
    }, 
    error: function (error) { 
     alert("error"); 
    } 
});