Craig Fox
Craig Fox

Reputation: 41

Uploading PDF Content Into An S3 Bucket

I'm trying to download PDF content with data from a remote location and upload the content into S3 as a pdf file. I'm using NodeJS, in the context of an AWS lambda. The s3.putObject parameter function resolves successfully, and a pdf file is saved into the S3 bucket as intended, but the document is blank when viewed, suggesting that all of the data may not have been passed to s3.putObject.

Here is my code.

const request = require('request')
const viewUrl = "https://link_to_downloadable_pdf/"
    
const options = {
  url: viewUrl,
  headers: {
    'Content-Type': 'application/pdf'
  }
};

request(options, function(err, res, body){
  if(err){return console.log(err)}
  const base64data = new Buffer(body, 'binary');
  const params = {
    Bucket: "myS3bucket",
    Key: "my-pdf.pdf",
    ContentType: "application/pdf",
    Body: base64data,
    ACL: 'public-read'
  };  
  
  s3.putObject(params, function(err, data) {
      if (err) {
        console.log(err);
      } else {
        callback(null, JSON.stringify(data))
      }  
  })

When I test the URL in Postman, it returns the PDF with data included. Any idea why the NodeJS code may not be doing the same thing?

Upvotes: 3

Views: 6805

Answers (1)

ene_salinas
ene_salinas

Reputation: 705

Can you try this code? :)

    import AWS from 'aws-sdk'
    const request = require('request')
    const S3 = new AWS.S3()

    var promise = new Promise((resolve, reject) => {
        return request({ url : 'https://link_to_downloadable_pdf/', encoding : null }, 
        function(err, res, body){

            if(err)
                return reject({ status:500,error:err })

            return resolve({ status:200, body: body})        
        })
    })

    promise.then((pdf) => {

        if(pdf.status == 200)
        {
            console.log('uploading file..')

            s3.putObject({
                Bucket: process.env.bucket,
                Body: pdf.body,
                Key: 'my-pdf.pdf',
                ACL:'public-read'
            }, (err,data) => {
                if(err)
                    console.log(err)
                else
                    console.log('uploaded')
            })
        }
    })

I'll be attentive to anything. hope to help you

Upvotes: 0

Related Questions