2

I'm trying to send a file using jQuery to my MVC controller but the action keeps receiving a null HttpPostedFileBase parameter.

HTML:

<input type="file" name="file" id="file" />
<input type="submit" name="submit" id="upload" value="Submit"/>

jQuery:

$(function () {
    $('#upload').click(function () {

        var data = new FormData($('#file')[0].files[0]);

        $.ajax({
            url: '@Url.Action("Upload", "Home")',
            type: 'POST',
            data: data,
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

Controller:

[HttpPost]
public virtual ActionResult Upload(HttpPostedFileBase file)
{
    // file = null
}

new FormData($('#file')[0].files[0]):

__proto__: FormData

$('#file')[0].files[0]:

lastModified: 1445429215528
lastModifiedDate: Wed Oct 21 2015 14:06:55 GMT+0200 (Central Europe Daylight Time)
name: "Google_Chrome_logo_2011.jpg"
size: 5506
type: "image/jpg"
webkitRelativePath: ""
__proto__: File

I pretty much copied the code from other examples that I found on the internet but somehow it is just not working.

1

3 Answers 3

8

Try this:

if (Request.Files.Count > 0)
{
   foreach (string file in Request.Files)
   {
      var _file = Request.Files[file];
   }
}

UPDATE

var $file = document.getElementById('file'),
    $formData = new FormData();

if ($file.files.length > 0) {
   for (var i = 0; i < $file.files.length; i++) {
      $formData.append('file-' + i, $file.files[i]);
   }
}

$.ajax({
   url: '/home/upload',
   type: 'POST',
   data: $formData,
   dataType: 'json',
   contentType: false,
   processData: false,
   success: function ($data) {

   }
 });
Sign up to request clarification or add additional context in comments.

2 Comments

Just tested it and Count result is 0
Is it possible with out FormData
0

This is my Solution

var formData = new FormData();
var files = $('input[type=file]');
for (var i = 0; i < files.length; i++) {
if (files[i].value == "" || files[i].value == null) {
 return false;
}
else {
 formData.append(files[i].name, files[i].files[0]);
}
}
var formSerializeArray = $("#Form").serializeArray();
for (var i = 0; i < formSerializeArray.length; i++) {
  formData.append(formSerializeArray[i].name, formSerializeArray[i].value)
}
$.ajax({
 type: 'POST',
 data: formData,
 contentType: false,
 processData: false,
 cache: false,
 url: '/Controller/Action',
 success: function (response) {
 if (response.Success == true) {
    return true;
 }
 else {
    return false;
 }
 },
 error: function () {
   return false;
 },
 failure: function () {
   return false;
 }
 });

Comments

0

If you are trying to send file to the controller you can use this approach:

var formdata = new FormData();
    formdata.append("YOUR_KEY", $("#ID_OF_Input_Type_File").prop('files')[0]);
    
    $.ajax({
        url: '/Home/UploadFile',
        type: "POST",
        data: formdata,
        contentType: false, // Not to set any content header  
        processData: false, // Not to process data
        success: function (result) {
        alert(result);
    },
        error: function (err) {
        alert(err);
    }
});

And your Controller will look like this:

public ActionResult UploadFile(HttpPostedFileBase YOUR_KEY)
{   
     // your file operations here....
     return Json(result, JsonRequestBehavior.AllowGet);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.