I am trying to upload file using Ajax to a Nodejs Server.
Ajax Code:
var url = 'http://<ip:port>/upload/';
var formValues = $("#files").get(0).files;
$.ajax({
url: url,
type: 'POST',
data: formValues,
processData: false,
cache: false,
beforeSend: function( xhr ) {
xhr.setRequestHeader('content-type', 'multipart/form-data');
},
success: function (data) {
console.log("Store details: %j", data);
Backbone.history.navigate('store');
window.location.reload();
}
});
I am using busboy in the Node Server and it is giving me this error when i trying to parse the request headers to initialize the busboy object.
Error: Multipart: Boundary not found
at new Multipart (/home/ubuntu/MoojicDashboard/node_modules/busboy/lib/types/multipart.js:58:11)
at Multipart (/home/ubuntu/MoojicDashboard/node_modules/busboy/lib/types/multipart.js:26:12)
at Busboy.parseHeaders (/home/ubuntu/MoojicDashboard/node_modules/busboy/lib/main.js:62:22)
at new Busboy (/home/ubuntu/MoojicDashboard/node_modules/busboy/lib/main.js:21:10)
But if i don't set the content-type to multipart/form-data the request is discarded by the busboy.
I even tried using multer package but it also give me the same error.( Later i found out it was build on busboy.)
I even tried setting contentType to false.
$.ajax({
url: url,
type: 'POST',
data: formValues,
processData: false,
cache: false,
contentType: false,
success: function (data) {
console.log("Store details: %j", data);
Backbone.history.navigate('store');
window.location.reload();
}
});
to force JQuery not to set default content-type but it didn't work too.
Setting contentType: 'multipart/form-data' also not worked and give me the same 'Multipart: Boundary not found' error. So anybody can help me out to get out of this error.
You should use the FormData API instead of trying to do it yourself. Then when you pass your FormData instance to $.ajax()
, it will automatically set the right headers for you. Here is an example.