3

I uploaded a png as attachment to a CouchDb database. When I have look at it via Futon it is fine, if I try to get it back via cradle it is corrupted. I used a snipptlet from the crade-test.js shipped with crade and modified it a bit:

      var response = {};
      var streamer = db.getAttachment(data.id,filename);
      streamer.addListener('response', function (res) {
        response.headers = res.headers;
        response.headers.status = res.statusCode;
        response.body = "";
      });
      streamer.addListener('data', function (chunk) { response.body += chunk; });
      streamer.addListener('end', function () {
        fs.writeFile('new-'+filename, response.body, function (err) {
          if (err) throw err;
            console.log('It\'s saved!');
          });
        });

The result is a corrupted png that is bigger than the input. I provided a working example here: http://jsfiddle.net/x8GZc/

samy
  • 14,832
  • 2
  • 54
  • 82
Nico
  • 31
  • 2

1 Answers1

1

The snippet you found is used with a text document (= basically a string). For binary data (e.g. images), you must set the correct encoding on the response object:

stream = client.database('images').getAttachment(req.params.id, filename);
// response is your HTTP response object
stream.on('data', function(chunk) {
    return response.write(chunk, "binary");
});
stream.on('end', function() {
    return response.end();
});
Leonhardt Wille
  • 557
  • 5
  • 20
  • 1
    Thanks for puting me on the right track, in my case I needed a fs.createWriteStream object. I'll updated the fiddle to a working solution: http://jsfiddle.net/x8GZc/1/ – Nico Jul 28 '11 at 08:22
  • 2
    It would be nice if you would approve my answer if it helped you. – Leonhardt Wille Aug 17 '11 at 19:02