2013-05-10 51 views
0

在我的項目中,我需要上傳一個文本文件。 我們正在使用MVC4 - Razr。 我想使用AJAX/Jquery/Javascript文件上傳,因爲它不會回發到表單。 這是我的代碼。它實際上傳文件,但之後它重定向 報告\ uploadfile將值爲true。 有沒有更好的方法來做到這一點。AJAX在MVC中上傳文件

這裏是我的代碼 @@@@@@@@@

@using (Html.BeginForm("uploadfile", "reports", FormMethod.Post, new {enctype = enter code here`"multipart/form-data"})) 
{ 
    <input type="file" name="FileUpload1" /><br/> 
    <input type="submit" name ="Submit" id="Uploadfile" value="Upload"/> 
} 

--controller代碼

[HttpPost] 
     public JsonResult UploadReports() 
     { 
      if (Request.Files[0].ContentLength > 0) 
      { 
       string uploadPath = "C:\\Upload";    
       string filename = Path.GetFileName(Request.Files[0].FileName); 
       Request.Files[0].SaveAs(Path.Combine(uploadPath, filename)); 

      } 
      return Json(true); 
     } 

回答

1

在我看來,最簡單的方式是利用jQuery Form Plugin。這樣,您就可以ajaxify文件上傳如下:

<script type="text/javascript"> 
    $(function() { 
      $('#myForm').ajaxForm({ 
      }); 
    }); 
</script> 

@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { @id = "myForm", enctype = "multipart/form-data" })) 
{ 
    <input type="file" name="FileUpload1" /><br /> 
    <input type="submit" name="Submit" id="Uploadfile" value="Upload" /> 
} 

和公共UploadReports方法,你可以接受FileUpload1參數:List<HttpPostedFileBase> FileUpload1

+0

感謝您的答覆。這是我正在尋找的。 – Henry 2013-05-16 00:28:05