0

I need to upload a file along with several other input data with Ajax to ASP.NET MVC. I do the following to accomplish this:

var formData=new FormData();
formData.Append("uploadedFile",$('input[type="file"]')[0].files[0]);
$.ajax({
    url: "/Test/TestFormData",
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    dataType:"json",
    type: 'POST'
});

I couldn't figure out how to handle this on the server side with proper model binding (if that's ever possible) so I decided to go by searching Form by keys:

  public class TestControler:Controller
    public void TestFormData(){
      var file=Request.Form["uploadedFile"];//file is null here
    }

The problem is the file is null when I try to access it. Here's the Request Headers and Payload:

Request

Is there anything additional I have to do to get the file on the server side?

Mikayil Abdullayev
  • 12,117
  • 26
  • 122
  • 206
  • Take help from this [link](http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html#) – Lali Sep 04 '15 at 06:52
  • Unfortunately that guy in the link you provided uses iFrame for this purpose. And besides it's PHP. – Mikayil Abdullayev Sep 04 '15 at 07:09
  • Its easier just to include the parameter in your POST method - `public ActionResult TestFormData(HttpPostedFileBase uploadedFile)` and if you have a form, then you can just use `var formdata = new FormData($('form').get(0));` which will serialize the form and any file inputs (refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681)) - although what your doing seems OK –  Sep 04 '15 at 07:25

1 Answers1

0

As often, @Stephen Muecke's reply helped me find a solution. Although I didn't get 100% what I needed but it's better than nothing. I did exactly what @Stephen suggested in this answer but in my case it didn't help. Don't have any clue as to why. So this is what I ended up with:

var formData=new FormData();
formData.append("uploadedFile",$('input[type="file"]')[0].files[0]);
var doc={};
doc.Subject="TestSubject";
doc.DocBody="Test body";
doc.Receiver="Someone@somewhere";
formData.append('doc',JSON.stringify(doc));


  public class TestControler:Controller
    public void TestFormData(HttpPostedFileBase uploadedFile){
      var doc=Request.Form["doc"];
    }

As you can see, I access the uploaded file and the doc object from different places. The argument name must match the one that we append to formData on the client side, otherwise the argument will be null.Don't know why but if I add another argument named doc that doesn't work. I mean it's null that's why I had to access it through Form["doc"].

Community
  • 1
  • 1
Mikayil Abdullayev
  • 12,117
  • 26
  • 122
  • 206