Marc Marc - 1 year ago 102
jQuery Question

File Upload with jquery AJAX and FormData

I am trying to upload a file from a form to a PHP Server via JQuerys AJAX method and the FormData method.

I use knockoutJS to trigger the submit action after pressing the upload button.

The HTML Form:

<form class="form-horizontal" method="post" enctype="multipart/form-data" data-bind="submit: addNewFile">
<legend>Add File</legend>

<div class="form-group">
<label for="inputFile" class="col-lg-2 control-label">File</label>
<input type="file" id="inputFile" name="inputFile">
<div class="form-group">
<button class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>


The triggered javascript-code:

self.addNewFile = function (content){
var formData = new FormData(content[1].files[0]);

url: '../api/addFile',
type: 'POST',
data: formData,
contenType: false,
processData: false})

The formData variable looks like this:

And the http request looks like this:

There is no file that is transfered to the server. The content-type is set to application/x-www-form-urlencoded but it should be multipart/form-data. What am I doing wrong?

Answer Source

The FormData constructor takes a HTMLFormElement, i.e. a form not a file, to add an individual file you have to use the append method

var formData = new FormData();

also you spelt contenType incorrectly it should be contentType, notice the 2 Ts together

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download