Nicholas Mattiacci
Nicholas Mattiacci

Reputation: 65

Node.js write raw image data

I'm writing a node.js server, and for part of the site, the user needs to be able to upload an image. When an image is uploaded, it's copy on the server is corrupt.

Here's the script for the body parser.

request.body = {};
var busboy = new Busboy({headers: request.headers});
busboy.on("field", function(fieldname, val) {
  request.body[fieldname] = val;
});
busboy.on("file", function(fieldname, file, filename) {
  var fileContents = "";
  file.on("data", function(data) {
    fileContents += data;
  });
  file.on("end", function() {
    request.body[fieldname] = {"filename": filename, "contents": fileContents};
  });
});
busboy.on("finish", function() {
  next(request, response);
});
request.pipe(busboy);

When a text file is uploaded, the server saves it just fine, but certain symbols in image files aren't sent or received correctly.

Upvotes: 2

Views: 753

Answers (1)

Nicholas Mattiacci
Nicholas Mattiacci

Reputation: 65

That's because data is a Buffer and by default, when you treat it like a string (by appending it to another string), the encoding is UTF8. The solution is don't treat it like a string, treat it like a buffer, then you won't end up with malformed code points. – Patrick Roberts

As Patrick said, the problem was in fileContents += data;. This converts the data buffer to a string, which can't contain the characters I needed. Instead, I added each data buffer to an array, then concatenated them all, and wrote that to a file.

Upvotes: 1

Related Questions