0

I have been trying to upload an image to s3 using multer and downloading it to a local path successfully using the below code.

routes.post('/updownload', upload.array('file'), function (req, res) {   
    var params = {  
        Bucket: "*******",  
        Key: "image1.jpeg"  
       };  
var file = fs.createWriteStream('./uploads/file4.jpeg');                     

 s3.getObject(params)  
.createReadStream()  
.on('error', function (err) {                   
         console.log('Error reading file: ' + err.message);
         file.end();
        })                 
        .pipe(file)  
        .on('error', function (err) {   
            err = true;  
            console.log('Error writing file:' + error.message);  
            file.end();   
        })   
        .on('finish', function (err) {                        
            file.end();   
            if (!err) {   
                console.log('Successfully downloaded file from S3');  
            }  
    });    
}); 

However, i am not sure, how do i send the response back to HTML with parameters like Headers, Body, Content-Type, status code and status message based on success/failure of image getting downloaded.
Kindly help and let me know if i am going in a correct path.

Priyanka
  • 95
  • 5
  • 12

2 Answers2

2

I know, it has been quite a long time to answer this question. But thought, this would help someone. I was able to solve the issue with below code given:

const params = {
      Bucket: '*********',
      Key: image1.jpeg,
    };

    res.set('Content-Type', 'image/jpeg');
    res.set('Content-Type', 'image/jpg');
    res.set('Content-Type', 'image/png');


    const stream = s3.getObject(params).createReadStream();
    stream.on('error', err => {
      logger.log({ level: 'error', messsage: 'stream error', error: `${err}` });
    });
    stream.pipe(res);
Priyanka
  • 95
  • 5
  • 12
0
  1. You will need to fully wait for the event emitter from S3 to finish completely before sending a response to the client. NodeJS 7: EventEmitter + await/async
  2. Once you have the data, you will need to transform the readable stream into a Buffer and determine the ContentType from the file you downloaded and use: res.send(Buffer): http://expressjs.com/en/api.html#res.send

Also see Node.js: How to read a stream into a buffer?

Cisco
  • 20,972
  • 5
  • 38
  • 60
  • Based on your first point, i can handle the response being sent to client in .on('finish', function (err) {} right? How would i get the data? – Priyanka Apr 08 '18 at 14:19
  • Or is there a better way to read the file directly from s3 and display it in frontend? – Priyanka Apr 09 '18 at 07:33
  • You will need to look into the documentation of the SDK for S3. I've not worked with it so I can't give an exact answer. The answer above is what you need to do in a nutshell. – Cisco Apr 09 '18 at 13:58