Ash Rhazaly
Ash Rhazaly

Reputation: 215

AWS Lambda - PDF Uploads to S3 return blank pages

I'm looking to upload a PDF statement that contains some pages of data however the PDF uploaded to S3 has been returning blank pages. It seems most of the solutions seem to revolve around converting the Buffer type to base64, I've tried that and I'd get a blank PDF.

I've manually added the binary media type on API Gateway multipart/form-data and it still results in a blank pdf.

How can I ensure the pdf is not a blank?

import { Handler, Context, Callback } from "aws-lambda";
import S3, { PutObjectRequest } from "aws-sdk/clients/s3";

import httpMultipartBodyParser from "@middy/http-multipart-body-parser";
import httpErrorHandler from "@middy/http-error-handler";
import cors from "@middy/http-cors";
import middy from "@middy/core";
import createError from "http-errors";

const s3 = new S3();

const anonymizer: Handler = async (
  event: any,
  _context: Context,
  callback: Callback
) => {
  const {
    emailAddress,
    pdf: { filename, mimetype, content },
  } = event.body;

  const uploadRequest: PutObjectRequest = {
    Bucket: `anon-${process.env["NODE_ENV"]}`,
    Key: `${emailAddress}/${filename}`,
    ContentType: mimetype,
    Body: content,
  };

  try {
    const { Location } = await s3.upload(uploadRequest).promise();
    callback(null, {
      statusCode: 200,
      body: JSON.stringify({ fileLocation: Location }),
    });
  } catch (error) {
    throw createError(error.statusCode, error.errorMessage, error);
  }
};

export const anonymizerHandler = middy(anonymizer)
  .use(httpMultipartBodyParser())
  .use(httpErrorHandler())
  .use(cors());

Upvotes: 0

Views: 1236

Answers (1)

Ash Rhazaly
Ash Rhazaly

Reputation: 215

Turns out it was adding the binary media type multipart/form-data on API Gateway, this had to be deployed and it took a while before the change took effect, and now I no longer get blank PDFs :).

Upvotes: 2

Related Questions