Matt Gaunt
Matt Gaunt

Reputation: 9821

Use NodeJS to upload file in an API call

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

Upvotes: 14

Views: 23859

Answers (3)

maerics
maerics

Reputation: 156534

Your code should work fine; it's the curl usage that's wrong. Try this instead:

$ curl -X POST --data-binary @test_file http://localhost:8080

Upvotes: 0

piggyback
piggyback

Reputation: 9264

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

Upvotes: 2

Matt Gaunt
Matt Gaunt

Reputation: 9821

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

Upvotes: 5

Related Questions