5

I'm trying to retrieve an image from s3 in node using the following:

app.get('/photos', function(req, res, next) {
var data = '';
s3.get('/tmp/DSC_0904.jpg').on('response', function(s3res){
    console.log(s3res.statusCode);
    console.log(s3res.headers);
    s3res.setEncoding('binary');
    s3res.on('data', function(chunk){
      data += chunk;
    });
    s3res.on('end', function() {
      res.contentType('image/jpeg');
      res.send(data);
    });
  }).end();
});

I'm open to suggestions as to why this doesn't work.

ben75
  • 29,217
  • 10
  • 88
  • 134
jbg
  • 993
  • 1
  • 11
  • 19
  • I get data, however it's mangled in some way such that it's not a valid jpg file. – jbg Sep 01 '11 at 08:17

3 Answers3

3

I was able to download an image by making the following modifications in the end event callback:

s3res.on('end', function() {
    res.contentType('image/jpeg');
    res.write(data, encoding='binary')
    res.end()
});

I was having the same issues as the original poster. I suspected that since we set the encoding on the incoming buffer to binary we needed to do the same on the output stream. After some research I found the write method which excepts an encoding type as a parameter.

Padraic
  • 80
  • 6
1

You might like to use AwsSum since it is fully featured and maintained. It also has an examples/ directory which has a load of Amazon S3 examples in there:

There is also an example of exactly what you need in the node-awssum-scripts repository which is separate from the node-awssum one:

Let me know if you get on ok or if you need any help. Disclaimer: I'm the author of AwsSum. :)

chilts
  • 451
  • 3
  • 12
0

I use this to get my images, and it works quite well..

//  Create the new file using fs
var new_file = fs.createWriteStream(destination_file);

//  Now grab the file from s3
aws_connection.getFile(f, function(err, res) {
    if(err) return err;

    res.on('data', function(chunk) {
        new_file.write(chunk);
    });
    res.on('end', function(chunk) {
        new_file.end();
    });
});
Jono
  • 143
  • 1
  • 4