user979331
user979331

Reputation: 11861

jQuery upload file returns empty

I am trying to upload a file via jQuery which I will use ajax to pass to .NET

Here is what I got on the jQuery side:

$("#attachmentItem-" + this.id).html('<input type="file" name="file" id="file-' + this.id + '" /><br/><input type="submit" value="Upload File" id="upload-' + this.id + '" />');
var id = this.id;
$("input[id=upload-" + this.id + "]").bind('click', function () {
    var formData = new FormData();
    var totalFiles = document.getElementById("file-" + id).files.length;
    for (var i = 0; i < totalFiles; i++) {
        var file = document.getElementById("file-" + id).files[i];
        console.log(file);
        formData.append("file-" + id, file);
    }
    console.log(formData);
});

formData returns FormData {} and file returns File {} and I don't know why.

Upvotes: 0

Views: 49

Answers (1)

Prahlad Yeri
Prahlad Yeri

Reputation: 3653

Your code is appending to the FormData object correctly, but you are missing on the code to fetch back the value of formData variable. Just replace:

console.log(formData);

with this:

console.log(formData.getAll("file-0")); //Assuming 0 is one of your IDs

You see, FormData is not a javascript Object that you can just write it to console. It is a browser built-in Object, so needs to be handled as such.

Upvotes: 1

Related Questions