Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use NodeJS to upload file in an API call

Tags:

node.js

I'm looking at using NodeJS to act as the server to build an API.

Ideally I'd love for there to be an API endpoint to send a set of information as well as a file which can be saved to the files system.

Most examples I've seen are for sending a file via a form, however I'd like to do this through a post request.

Does anyone know how I could achieve this (if it's at all possible)?

At the moment what I'd like to achieve is something along the following lines:

app.post('/Some/Endpoint/', controller.handleSomeEndpoint, function(request, response) {
    response.send('Finished Request');
});

exports.handleSomeEndpoint = function(request, response, next) {
    var bodyarr = []
    request.on('data', function(chunk){
      bodyarr.push(chunk);
    })
    request.on('end', function(){
      console.log( bodyarr.join('') );
    })
}

But the data and end never get called if I run a curl command along the lines of:

curl http://127.0.0.1:5000/Some/Endpoint/ -F 'test=@test_file'

Cheers, Matt

like image 793
Matt Gaunt Avatar asked Jan 11 '12 17:01

Matt Gaunt


2 Answers

The answer seems to be that expressJS doesn't use the same method of handling a post file as the http module in nodejs.

All that was needed was including a directory for the files to be written to:

app.use(express.bodyParser({uploadDir:'./uploads'}));

Which I found here:

http://www.hacksparrow.com/handle-file-uploads-in-express-node-js.html

like image 182
Matt Gaunt Avatar answered Oct 26 '22 04:10

Matt Gaunt


I would suggest you to use Formidable to avoid anonymous file uploading.

like image 2
piggyback Avatar answered Oct 26 '22 04:10

piggyback