Daniel Gray
Daniel Gray

Reputation: 17

Concatting buffer returns corrupt image node.js

I am attempting to make a image uploading service. I am currently taking the data sent, storing it in an array and then using the concat function to put it together. Then I am trying to save the data received (an image). But, when you look at the outputted image, it is corrupt.

app.post('/upload', function(req, res) {
var buffers = []
req.on("data", function(chunk) {
    buffers.push(chunk)
})
req.on("end", function() {
    console.log(buffers);
    Buffer.concat(buffers);
    fs.writeFileSync(`/Users/dangray2004/Documents/HTML/Dimg/images/image1.png`, buffers)
})

res.render('upload', {

})
})

If anyone could help it would be much appreciated.

Upvotes: 1

Views: 1570

Answers (2)

ottomeister
ottomeister

Reputation: 5808

The reason why the original code isn't working is that Buffer.concat() does not modify the array it receives as an argument. It returns a new Buffer whose contents are the concatenation of the members of the array argument. Right now your code here:

  Buffer.concat(buffers);

does not collect the returned Buffer, and this:

  fs.writeFileSync('filename', buffers)

writes the content of the original array of buffers to the file -- which is almost what you want, except that it will insert a comma between each member's data as it writes the members to the file. Those extra commas corrupt the image data.

To fix, replace those two lines with code that collects the new Buffer returned by concat and writes it to the file:

  var buffer = Buffer.concat(buffers);
  fs.writeFileSync('filename', buffer);

or just:

  fs.writeFileSync('filename', Buffer.concat(buffers));

Upvotes: 4

Terry Lennox
Terry Lennox

Reputation: 30685

You could try this approach out, it works nicely for me:

app.post('/upload', function(req, res) {
    var buffer = new Buffer('');
    req.on('data', function(chunk) {
      console.log("data chunk: " + chunk.length);
      buffer = Buffer.concat([buffer, chunk]);
    });
    req.on("end", function() {
        console.log("req.end: " + buffer.length);
        fs.writeFileSync("test.png", buffer);
    })
});

Upvotes: 1

Related Questions