1

I am trying to open a file from a s3 bucket using angular as a pdf. To do this, I have a node service running which gets the object, which I call from angular. Then I'm trying to open in angular as a pdf. Is there something I am missing? When I open the PDF, it shows up as a blank (white) document.

Below is my node code:

const streamToString = (stream) =>
new Promise((resolve, reject) => {
  const chunks = [];
  stream.on("data", (chunk) => chunks.push(chunk));
  stream.on("error", reject);
  stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
});

const readFile = async function getObj(key) {
  const params = {
    Bucket: vBucket,
    Key: key,
  };
  const command = new GetObjectCommand(params);
  const response = await client.send(command);
  const { Body } = response; 
  return streamToString(Body);
};

And here I am consuming in angular and opening as PDF

The service:

  getObj(key: String): Observable<any>{
    const httpOptions = {
      'responseType'  : 'arraybuffer' as 'json'
       //'responseType'  : 'blob' as 'json'        //This also worked
    };
    return this.http.get<any>(environment.s3Ep + '/getfile?key=' + key, httpOptions );
  }

And code consuming the service:

this.s3Svc.getObj(key).subscribe(
  res => {
    let file = new Blob([res], {type: 'application/pdf'});
    var fileURL = URL.createObjectURL(file);
    window.open(fileURL);
  } 
);
elesh.j
  • 192
  • 1
  • 3
  • 15
  • I just started experiencing the same issue. it was working fine, nothing changed and now suddenly PDF's are coming down blank when using GetObjectCommand – niltoid Oct 26 '22 at 16:58

1 Answers1

0

I started experiencing the same issue. Found a solution, replacing streamToString with streamToBuffer as follows:

const streamToBuffer = async (stream: Readable): Promise<Buffer> => {
  return new Promise((resolve, reject) => {
    const chunks: Array<any> = []
    stream.on('data', (chunk) => chunks.push(chunk))
    stream.on('error', reject)
    stream.on('end', () => resolve(Buffer.concat(chunks)))
  })
}

and the code that consumes it:

  const command = new GetObjectCommand({ Bucket, Key })
  const data = await s3.send(command)
  const content = await streamToBuffer(data.Body as Readable)
  fs.writeFileSync(destPath, content)

In my case I'm writing to a PDF file. Writing as a string retrieved from streamToString or writing it as buffer.toString() resulted in the blank PDF.

niltoid
  • 819
  • 1
  • 7
  • 17