1

I need to pass my upload file to my controller using jquery ajax.

JS:

$('#btnpopupreg').click(function () {
        $.ajax({
            type: 'POST',
            url: '/Membership/Register',
            data: $('#frmRegister').serializeArray(),
            dataType: 'json',
            headers: fnGetToken(),
            beforeSend: function (xhr) {

            },
            success: function (data) {
                //do something
            },
            error: function (xhr) {

            }
        })
})

View:

@model Test.RegisterViewModel

@{
       using Html.BeginForm(Nothing, Nothing, FormMethod.Post, New With {.id = "frmPopUpRegister", .enctype = "multipart/form-data"})
}

<input type="file" />
//rest of my strongly typed model here
<input type="button" value="BUTTON" />
//rest of the code here

Controller:

[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]

public void Register(RegisterViewModel model)
{

    if (Request.Files.Count > 0) { //always 0

    }

    if (ModelState.IsValid) {
          //do something with model
    }
}

I can get the model value just fine but Request.Files always returns null. I also tried using HttpPostedFileBase but it also always return null

[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]

public void Register(RegisterViewModel model, HttpPostedFileBase files)
{
    //files always null

    if (ModelState.IsValid) {
          //do something with model
    }
}
tickwave
  • 3,335
  • 6
  • 41
  • 82

3 Answers3

3

First you need to give you file control a name attribute so it can post back a value to your controller

<input type="file" name="files" /> // 

Then serialize your form and the associated file(s)

var formdata = new FormData($('form').get(0));

and post back with

$.ajax({
  url: '@Url.Action("Register", "Membership")',
  type: 'POST',
  data: formdata,
  processData: false,
  contentType: false, 
  success: function (data) {
    ....
  }        
});

Note also the file input needs to be inside the form tags

  • not working, it doesn't even hit my controller. If I remove processData and contentType, it works, but files still null. – tickwave Mar 31 '15 at 11:12
  • It does work (check the url is correct). There must be other issues with your code - your view indicates there aren't even any controls within the form. –  Mar 31 '15 at 11:15
  • Is it possible to do the same thing but to have the HttpPostedFileBase in the RegisterViewModel model? – smoksnes Jul 20 '16 at 10:55
  • 1
    @smoksnes, Absolutely, and that is the preferred way to do it. –  Jul 20 '16 at 10:57
0

You need to use FormData with combination of contentType, processData setting to false:

    var formData = new FormData();
        formData.append("userfile", $('#frmRegister input[type="file"]')[0].files[0]);
        // append the file in the form data
    $.ajax({
      type: 'POST',
      url: '/Membership/Register',
      data: formdata, // send it here
      dataType: 'json',
      contentType:false, // this
      processData:false, // and this should be false in case of uploading files
      headers: fnGetToken(),
      beforeSend: function(xhr) {

      },
      success: function(data) {
        //do something
      },
      error: function(xhr) {

      }
    })
Jai
  • 74,255
  • 12
  • 74
  • 103
0
<input type="file" id="LogoImage" name="image" />
<script>

var formData = new FormData($('#frmAddHotelMaster').get(0));

var file = document.getElementById("LogoImage").files[0];

formData.append("file", file);


        $.ajax({
            type: "POST",
            url: '/HotelMaster/SaveHotel',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (response) {
                swal({
                        title: "Good job!",
                        text: "Data Save successfully!",
                        type: "success"
                    });
                    $('#wrapper').empty();
                    $('#wrapper').append(htmlData);
            },
            error: function (error) {
                alert("errror");
            }
        });
</script>

public ActionResult SaveHotel(HotelMasterModel viewModel, HttpPostedFileBase file)
{

            for (int i = 0; i < Request.Files.Count; i++)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
                file.SaveAs(path);
            }
return View();
}
4b0
  • 21,981
  • 30
  • 95
  • 142