0

I have the following lambda function. It received an XML, looks through it, finds a base64 pdf file and tries to upload it to S3.

index.js

const AWS = require('aws-sdk');
const xml2js = require('xml2js');
const pdfUpload = require('./upload_pdf');
const s3 = new AWS.S3();

exports.handler = async (event, context, callback) => {
    let attachment;
    xml2js.parseString(event.body, function(err, result) {      
      attachment = 
        result.Attachment[0].Data[0];

      if (attachment) {
        pdfUpload(attachment); 
      }

    });

    return {
      statusCode: 200
    }
};

upload_pdf.js

/**
 *
 * @param  {string}  base64 Data
 * @return {string}  Image url
 */
const pdfUpload = async (base64) => {

  const AWS = require('aws-sdk');
  const s3 = new AWS.S3();
  const base64Data = new Buffer.from(base64, 'base64');

  // With this setup, each time your user uploads an image, will be overwritten.
  // To prevent this, use a different Key each time.
  // This won't be needed if they're uploading their avatar, hence the filename, userAvatar.js.
  const params = {
    Bucket: 'mu-bucket',
    Key: `123.pdf`, 
    Body: base64Data,
    ACL: 'public-read',
    ContentEncoding: 'base64', 
    ContentType: `application/pdf` 
  }

  let location = '';
  let key = '';
  try {
    const { Location, Key } = await s3.upload(params).promise();
    location = Location;
    key = Key;
  } catch (error) {
     // console.log(error)
  }

  console.log(location, key);

  return location;
}

module.exports = pdfUpload;

No matter what I do, the file does not get uploaded. I have checked the permissions, and the lambda has access to the bucket. Running the lambda I'm not receiving any errors either. Can anybody see what might be wrong here?

1
  • You are using an async function. Lambda is probably returning long before the file is uploaded. Commented Apr 17, 2020 at 4:43

1 Answer 1

1

First, as an advice, I think you should put more logs to see at which steps the function is stuck / failing

The second thing you can try is to put await

        await pdfUpload(attachment); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it makes sense. I can see the code in upload_js at least getting executed now. However the attachment string never gets to that file, and I'm getting an error that it is undefined. Even though I can console.log it inside index.js and see it just fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.