0

I need to upload multiple files in mvc4 using ajax,and I tried to upload files using Ajax in mvc 4 with below code:

$("input[type='file']").on("change", function () {
    $("#upload").submit();
});
$("#upload").submit(function () {
    var l = window.location;
    var base_url = l.protocol + "//" + l.host;
    var formData = new FormData();
    var totalFiles = document.getElementById("FileUpload").files.length;
    for (var i = 0; i < totalFiles; i++) {
        var file = document.getElementById("FileUpload").files[i];
        formData.append("FileUpload", file);
    }
    $.ajax({
        type: "POST",
        url: base_url + '/ProductSpecific/Upload',
        data: formData,
        dataType: 'json', encode: true,
        async: false,
        processData: false,
        cache: false,
        success: function (data, status, jqXHR) {   
        },
        error: function (jqXHR, textStatus, errorThrown) {     
        }
    });
});

I just alert totalFiles inside the script ,it returns the number of files selected for upload.

My controller code is:

public ActionResult Upload()
{
    for (int i = 0; i < Request.Files.Count; i++) {
        var file = Request.Files[i];
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/Images/img"), fileName);
        file.SaveAs(path);
    }
    return View();
}

Since file upload is styled using and css and view page code is:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "formbuttons", enctype = "multipart/form-data" }))
{
    <span id="upload" class="fileUpload">Upload
        <input id ="FileUpload" type="file" class="uploadfile" name="FileUpload" multiple="multiple" />
    </span>
}

But always Request.Files.Count is 0 in the controller.

tereško
  • 58,060
  • 25
  • 98
  • 150
Neethu
  • 85
  • 4
  • 9
  • You need to also set `contentType: false,` but you will find this a lot easier to just use `var formdata = new FormData($('#formbuttons').get(0));` to serialize all form values including files (refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) for more detail) –  Sep 09 '15 at 05:34
  • Yes it is working !!!! thank you Stephen Muecke – Neethu Sep 09 '15 at 05:43

2 Answers2

0

Please checkout below code. I have removed content type field and added enctype: 'multipart/form-data'

  $.ajax({
                type: "POST",
                url: base_url + '/ProductSpecific/Upload',
                // data: {  category: $('#ProductCategory').val(), description: $('#Description').val() },
                data: formData,
                enctype: 'multipart/form-data',
                async: false,
                processData: false,
                cache: false,
                //contentType: 'application/json; charset=utf-8',
                success: function (data, status, jqXHR) {

                },
                error: function (jqXHR, textStatus, errorThrown) {


                }
            });
prashant
  • 2,181
  • 2
  • 22
  • 37
0

You also need to include the contentType: false, ajax option

$.ajax({
  type: "POST",
  url: '@Url.Action("Upload", "ProductSpecific")', // recommended
  contentType: false, // add this
  data: formData,
  dataType: 'json', 
  encode: true,
  async: false,
  processData: false,
  cache: false,
  success: function (data, status, jqXHR) {
    ...

Side note: You can simplify your code for adding the files to FormData by simply using

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

which will serialize all the form controls including file inputs. You can add a parameter to your method to bind the files

public ActionResult Upload(IEnumerable<HttpPostedFileBase> FileUpload)
{
  ....
}