I did not know what to write as the title, as I am having a very strange issue. What I am trying to do is upload and save *.html files on server. Following is the code structure:
Jade Template (Form):
#template-uploader
form(enctype='multipart/form-data')
input(name='file', type='file')
input#upload-template(type='button', value='Upload')
JS (Form Handle):
//Upload Btn Click Event Handler
$('#upload-template').on('click', function(){
event.stopPropagation();
event.preventDefault();
uploadFiles();
});
// Upload the files using AJAX
function uploadFiles()
{
var formData = $('input[type=file]')[0].files;
$.ajax({
url: 'template/upload',
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
// For handling the progress of the upload
}
return myXhr;
},
data: formData[0],
cache: false,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
console.log('Data');
console.log(data);
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + errorThrown);
// STOP LOADING SPINNER
}
});
}
Server (Node.js)
//Route handler for template file uploaded
router.post('/template/upload', function(req, res) {
console.log('Uploading Files');
console.log(req.files);
});
Now the issue is that when I select a file and click the upload button, an ajax request is made. I have logged the data that I am sending and seems good at the client end. On server side there are however two issues.
req.files
param. I did this before in Express 3.x without any issues. Now I am using Express 4.x, and maybe I am missing something.console.log('Uploading Files')
message. But I don't receive any error or success message on client side. I also don't see in terminal that a POST request was received for the mentioned route. However after 2 minutes (every time), the terminal logs the request received for the route including the console.log()
message. And this is when I get a response on client side.Terminal Logging:
Uploading Files
undefined
POST /dashboard/template/upload 200 **120004ms**
Uploading Files
undefined
This is beyond me. I don't think there are any pre-flight checks generated by client side.If someone can provide insight as to what might the issue be, that'd be great.
req.files
from Express 3 is from the body parser middleware. In 4.x, this is no longer packaged with Express. You can install multer
and include it as explained in the docs to enable req.files
.