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">
                        <fieldset>
                            <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>       
                            <div class="form-group">
                                    <button class="btn btn-default" data-dismiss="modal">Cancel</button>
                                    <button type="submit" class="btn btn-primary">Save</button>
                            </div>

                        </fieldset>
                        </form>          

The triggered javascript-code:

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

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

The formData variable looks like this: http://i.stack.imgur.com/jZ06z.png

And the http request looks like this: http://i.stack.imgur.com/0Whfe.png

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?


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

var formData = new FormData();
formData.append('file',content[1].files[0]);

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

链接地址: http://www.djcxy.com/p/22226.html

上一篇: Java读取数据POST内容

下一篇: 使用jQuery AJAX和FormData进行文件上传