Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Covert S3 Buffer Data to PDF File

I am using an express route to get the s3 object via the AWS SDK:

router.get('/myRoute', (req, res) => {
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
s3.getObject({Bucket: 'my-bucket', Key: 'my-key'},
    function (error, data) {
        if (error != null) {
            // console.log(error)
            return res.send("Failed to retrieve an object: " + error.message);
        } else {
            console.log("data: ", data)
            return res.json(data)

        }
    });
});

The console output from above is:

 data:  {
  AcceptRanges: 'bytes',
  LastModified: 2022-06-06T01:29:41.000Z,
  ContentLength: 327626,
  ETag: '"8c9626sa6fd1d5bf3s990c36d607614b"',
  VersionId: 'GoEUVUP9eecY5rRRekhoG8PDtW0lp.dy',
  ContentType: 'application/pdf',
  Metadata: {},
  TagCount: 1,
  Body: <Buffer 25 50 44 46 2d 31 2e ... 327576 more bytes>
}

The react client code looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    const response = await fetch("/api/aws/brochure")
.then(res => res.json())
.then((data) => {
    console.log(typeof(data.Body.data))
    const fileURL = window.URL.createObjectURL(new Blob([new int8Array(data.Body.data).buffer]));

    //Open the URL on new Window
    const pdfWindow = window.open();
    pdfWindow.location.href = fileURL;   
});

The result is:
enter image description here

>Solution :

While initializing the blob object, you should specify the type which is a string indicating the MIME type of the data contained in the buffer.

So to create the blob, use below signature

var blob = new Blob([new int8Array(data.Body.data).buffer], type: "application/pdf");

Read more about blob here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading