How to receive a byte array inside a JSON

If the below variable is assumed to represent the structure of responseText:

responseText = {
      result: true,
      value: <the pdf byte array>,
      errorMessage: null
}

responseText.value is the byte array. If the byte array is already typed as Uint8Array then this would work.

(Note: Other Typed Arrays exist, so choose which ever one suits your case best):

var blob = new Blob([response.value], { type: 'application/pdf'});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob);
} else {
    var a = document.createElement("a");
    document.body.appendChild(a);
    var fileURL = URL.createObjectURL(blob);
    a.href = fileURL;
    a.download = 'test';//filename
    a.click();
}

However, if there is a string array, or integer array, of bytes like below:

responseText.value = [145, 229, 216, 110, 3]

and it needs to be converted to a typed byte array, then the below would work:

var ba = new Uint8Array(responseText.value);

or

var ba = new Uint8Array([145, 229, 216, 110, 3]);

Therefore,

var blob = new Blob([ba], { type: 'application/pdf'}); 

This way the byte array can be used to create a blob, so the file is downloaded when the click event fires.


You should convert bytes to base64 String and on UI read bytes from it.