Home > other >  Covert S3 Buffer Data to PDF File
Covert S3 Buffer Data to PDF File

Time:06-20

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:

    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

CodePudding user response:

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.

  • Related