-1

This question is a follow-up from this answer. I'm asking it as a question because I don't have enough reputation to make comments.

I am trying to write an Android app that takes an image and sends it to a Node.js server.

I found this code in the post linked above, but it leaves me with a raw buffer of data. How can I save the contents of this buffer as a JPEG image?

app.post('/upload-image', rawBody, function(req, res) {
    if (req.rawBody && req.bodyLength > 0) {

        // TODO save image (req.rawBody) somewhere

        // send some content as JSON
        res.send(200, {
            status: 'OK'
        });
    } else {
        res.send(500);
    }
});

function rawBody(req, res, next) {
    var chunks = [];

    req.on('data', function(chunk) {
        chunks.push(chunk);
    });

    req.on('end', function() {
        var buffer = Buffer.concat(chunks);

        req.bodyLength = buffer.length;
        req.rawBody = buffer;
        next();
    });

    req.on('error', function(err) {
        console.log(err);
        res.status(500);
    });
}
IronFlare
  • 2,287
  • 2
  • 17
  • 27
  • Are you somehow validating or screening the file type on the client's device or on the server? If someone uploads a PNG, there's no way to save it as a JPEG without converting it first. – IronFlare Aug 05 '19 at 18:10
  • Hi, thnks for your response. there is no screening or validating. I just need to upload a picture from the app on the user's phone to the server for processing with matlab. – StackOverflowBeginner Aug 08 '19 at 07:04

1 Answers1

0

You can simply use writeFile

Pass the file path as first argument, your buffer as second argument, and a callback to execute code when the file has been written.

Alternatively, use writeFileSync, a synchronous version of writeFile which doesn't take a callback

Guerric P
  • 30,447
  • 6
  • 48
  • 86