0

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.

rhernandez
  • 304
  • 2
  • 11
  • the data passed to the ajax request should be a string, object or array ... http://api.jquery.com/jquery.ajax/ – rafaelcastrocouto Oct 16 '14 at 17:41
  • possible duplicate of [Sending multipart/formdata with jQuery.ajax](http://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax) – mscdex Oct 16 '14 at 18:03
  • A gist that shows how to use busboy to upload multiple files and do a few checks on the file such as size, mimetype, etc https://gist.github.com/rhamedy/8f29ec90a00fcf8fec8f2c82bd34d10e – Raf Feb 26 '17 at 21:02

0 Answers0