Sign in
Log inSign up

Upload PDF files to S3 bucket

Karolis Stulgys's photo
Karolis Stulgys
·Oct 8, 2021·

2 min read

Upload PDF files to S3 bucket

I was working on my side project and I wanted to upload a pdf file to my aws S3 bucket. On the frontend I was using react-pdf - great library for generating pdfs on the frontend with react. The react-pdf library provides a blob as render prop which is a pdf file so I thought uploading this to my S3 bucket should be easy. It was not the case. The issue was with incorrect blob object for S3.

After multiple attempts and errors finally came across to working solution.

Frontend code:

            function toBase64(blob) {
              const reader = new FileReader();
              return new Promise((res, rej) => {
                reader.readAsDataURL(blob);
                reader.onload = function () {
                  res(reader.result);
                };
              });
            }

            const uploadedUrl = toBase64(pdfBlob).then((blob) => {
              return axios
                .post("/api/upload-poster", blob, {
                  headers: {
                    "Content-Type": "application/pdf",
                  },
                })
                .then(({ data }) => data.uploaded.Location);
            });

First we need to create a base64 blob from the blob that is provided by react-pdf. Then we post that blob to our endpoint i.e. /api/upload-poster

Backend code:

      const base64 = req.body;
      const base64Data = Buffer.from(base64.replace(/^data:application\/\w+;base64,/, ""), "base64");
      const params = {
        Bucket: "my-bucket-name,
        Key: Date.now().toString() + ".pdf", // some uuid
        Body: base64Data,
        ContentEncoding: "base64", // required
        contentType: "application/pdf",
      };

      const uploaded = await S3.upload(params).promise();
      res.status(200).json({ uploaded });

We need to get the base64Data from that blob (which is base64 here) passed via api.

And this is all the song and dance needed to upload a pdf to S3.

I hope this helps and works for you 🙌

FYI I might be available for contract projects. Check it out ❤️ 👇

linktr.ee/imkarolis