admin管理员组

文章数量:1429446

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.

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.

Share Improve this question edited Oct 26, 2014 at 12:15 ben75 28.8k12 gold badges94 silver badges138 bronze badges asked Aug 30, 2011 at 14:45 jbgjbg 1,0031 gold badge12 silver badges19 bronze badges 1
  • I get data, however it's mangled in some way such that it's not a valid jpg file. – jbg Commented Sep 1, 2011 at 8:17
Add a ment  | 

3 Answers 3

Reset to default 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 ining 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.

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:

  • https://github./appsattic/node-awssum/

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

  • https://github./appsattic/node-awssum-scripts/blob/master/bin/amazon-s3-download.js

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

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();
    });
});

本文标签: javascriptNodejs knox s3 image retrievalStack Overflow