0

We have an API that gives pdf files as a byte array,we are trying to convert that byte array response into pdf file

const axios = require('axios')
const fs = require('fs')
const {Base64} = require('js-base64');



axios.post("some api....")
  .then((response) => {
   

    var u8 = new Uint8Array(response.data.success);
    var decoder = new TextDecoder('utf8');
    var b64encoded = btoa(decoder.decode(u8));

    var bin = Base64.atob(b64encoded);
    fs.writeFile('file.pdf', bin, 'binary', error => {
        if (error) {
            throw error;
        } else {
            console.log('binary saved!');
        }
    });


  })

To do this we have first converted the byte array into a base 64 string and then converted that base64 string into a file, but after that opening a pdf file, the file is broken

we have also tried converting directly byte array into the file in the node but still getting broken file

Also tried the same approach in python but got same issue

import requests
import json
import base64

url = 'some api....'

x = requests.post(url, json = {})

# print(x.json()['success'])

dataStr = json.dumps(x.json()['success'])

base64EncodedStr = base64.b64encode(dataStr.encode('utf-8'))


with open('file.pdf', 'wb') as theFile:
  theFile.write(base64.b64decode(base64EncodedStr))

API response for byte array

[84,47,81,57,67,85,108,115,85,1................]

Saurabh
  • 1,592
  • 2
  • 14
  • 30
  • Does this answer your question? [How to write a file from an ArrayBuffer in JS](https://stackoverflow.com/questions/31581254/how-to-write-a-file-from-an-arraybuffer-in-js) – derpirscher Nov 03 '22 at 14:58
  • Check with an hex editor if the resulting file starts with the same bytes as your received Uint8Array. If yes, it might as well be, that your API sent an invalid response ... – derpirscher Nov 03 '22 at 15:00

1 Answers1

0

Just transfer data from response to file as stream:

const writeStream = createWriteStream('file.pdf');
response.data.pipe(writeStream);
Volodymyr Sichka
  • 531
  • 4
  • 10