I'm trying to do a simple file upload using jQuery. I have a file input in my HTML like so:
<form id="PhotoUploadForm" action="/some/correct/url" method="post" enctype="multipart/form-data">
<input type="file" id="uploadPhoto" accept="image">
</form>
I also have some JavaScript / jQuery bound to the change event of the input, like so:
$('#uploadPhoto').on("change", function (event) {
var fileData = this.files[0];
var data = new FormData();
data.append('image',fileData);
data.append('content','What could go wrong');
console.log(data.image, data.content); // this outputs 'undefined undefined' in the console
$.ajax ({
url: "/some/correct/url",
type: 'POST',
data: data,
processData: false,
beforeSend: function() {
console.log('about to send');
},
success: function ( response ) {
console.log( 'now do something!' )
},
error: function ( response ) {
console.log("response failed");
}
});
});
I noticed I was getting a 500 error! Most likely the data is incorrect, I know the URL is good. So I tried to output the data to the console and I noticed that my data appends return 'undefined'
console.log(data.image, data.content); // this outputs 'undefined undefined' in the console
when I console.log(data) I get the following:
FormData {append: function}__proto__: FormData
Am I doing something wrong here? Why are data.image & data.content undefined? When I output the this.files[0] I get the following:
File {webkitRelativePath: "", lastModified: 1412680079000, lastModifiedDate: Tue Oct 07 2014 13:07:59 GMT+0200 (CEST), name: "2575-Web.jpg", type: "image/jpeg"…}lastModified: 1412680079000lastModifiedDate: Tue Oct 07 2014 13:07:59 GMT+0200 (CEST)name: "2575-Web.jpg"size: 138178type: "image/jpeg"webkitRelativePath: ""__proto__: File
So the issue isn't with the image. Am I correct?
var fileData = $(this).files[0];$(this).files[0]will cause error.contentType: falsein the ajax request so that jQuery will set it properly