Modermo
Modermo

Reputation: 1992

Uploading stream data to Amazon S3

I'm try to push an svg QR code to S3 on my node app.

From what I understand, I should be uploading a Buffer to S3. When I inspect qrResult, I don't see one anywhere. Perhaps I'm fundamentally misunderstanding the concept of writeStreams, and how to pipe data to an S3 upload, but I can't seem to figure this out...

let fileName = 'qrCode'

let qrCode = Qr.image('The ultimate test', { type: 'svg' }); 
let output = fs.createWriteStream(fileName)
let qrResult = qrCode.pipe(output)



let s3bucket = new Aws.S3({
   accessKeyId: env.AWS_ACCESS_KEY
   secretAccessKey: env.AWS_SECRET,
   Bucket: env.S3_BUCKET_NAME,
});


let params = {
   Bucket: env.S3_BUCKET_NAME,
   Key: fileName,
   Body: qrResult,
 };


s3bucket.upload(params, function (err, qrResult) {
   if (err) {
     console.log('error in callback');
     console.log(err);
   }

   console.log('success');
   console.log(qrResult);
});

Upvotes: 0

Views: 2212

Answers (2)

Anshuman Jaiswal
Anshuman Jaiswal

Reputation: 5462

You may need to add ContentType & ACL in your params as:

let params = {
  Bucket: env.S3_BUCKET_NAME,
  Key: fileName,
  Body: qrResult,
  ContentType: 'image/svg+xml',
  ACL: 'public-read'
};

BTW I can't see file object in your code.

Also use putObject rather than upload like:

s3bucket.putObject(params...

Upvotes: 1

CoffeAbuser
CoffeAbuser

Reputation: 476

Key rappresent the name of qrCode and data is the qrCode itself.

So you can define a function that create the params, something like that:

aws.config.update({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});
const s3 = new aws.S3({
  params: {
  Bucket: process.env.S3_BUCKET
  }
const data = createParams(name,data);
s3.putObject(data, (err, response) => {....});

createParams(qrName, qrCode) {
let data = {
 Key: file.name,
 Body: file.data,
 ContentType: 'image/svg+xml',
 ACL: 'public-read'
}
 return data
}

Data is the output of your write stream or your qrCode

Upvotes: 0

Related Questions