I'm having some trouble sending data via Ajax to upload a file, if I send the data from the form directly, it works with the following code:
var fs = require('fs');
var fstream;
var folder = 'public/images/tmp/';
var path;
var images = [];
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
if(filename){
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder,0744);
}
path = folder+ filename;
fstream = fs.createWriteStream(path);
file.pipe(fstream);
} else {
path= undefined;
}
images.push(path);
res.send(images);
});
And the files are sent to the temp folder in the server. But I need to return images to my javascript, so with that data I can perform other actions.
Now, the options I am thinking are: 1- Find some way to avoid "data.send()" to redirect my form to the result view 2- Send the data with Ajax using a code similar to:
$.ajax( {
url: '/media',
type: 'POST',
data: new FormData(document.getElementById('#myFormId')),
success: //do things,
error: //do other things
});
but it doesn't work, I don't know wich format I should send my data to the POST function so it can work with busboy or if there is another way to copy the files to the server.
Thanks.