Henry
Henry

Reputation: 883

AJAX Upload file in MVC

In My project I need to upload a text file. We are using MVC4 - Razr. I want to use AJAX/Jquery/Javascript file upload as It doesn't post back to the form. Here is my code. Its actually uploading the file but after that it redirects to reports\uploadfile will the value true. Is there any better way of doing this.

Here is my code @@@@@@@@@

 @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 code

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

Upvotes: 0

Views: 1623

Answers (1)

IUnknown
IUnknown

Reputation: 22478

The easiest way in my opinion is to utilize jQuery Form Plugin. This way you can ajaxify file upload as below:

<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" />
}

And in the public UploadReports method you can accept FileUpload1 parameter: List<HttpPostedFileBase> FileUpload1

Upvotes: 1

Related Questions