How to read RAW JSON in Angular JS from HTTP get method, when response type is arraybuffer?
Instead of expecting arraybuffer
why not expect application/json
all the time, then when you return your data that's supposed to create your pdf, do a base64 of the data, put it in a json object and return it to the client
Even when you throw an exception you still expect JSON
. Your response from server side could be something like:
{ responseCode: // your response code according to whether the request is success or not, responseMessage: // success or fail data: // your base64 encoded pdf data(the data that if the request is successful will be returned), note it will be returned as a normal string} // I'm hoping you know how to base64 encode data
Then in your client side(Javascript), perform an if
if(data.responseCode == //errorCode) { alert(data.responseMessage);} else { // Unpack data var myPdfData = // base64 decode(data.data) // Do logic to create and open/download file}
You don't even need to decode the data, you just create a blob object, then trigger a download from the blob
If the responsetype is arraybuffer
, to view it, you should convert it into a blob and create a objectUrl from that blob, and the download it or open in a new tab/browser window to view it.
Js:
$http.get('your/api/url').then(function(response) {var blob = new Blob([response.data], { type: 'application/pdf' }); var downloadUrl = URL.createObjectURL(blob); $timeout(function () { var link = document.createElement('a'); link.download = 'SOME_FILE_NAME'+ '.pdf'; link.href = downloadUrl; link.click(); }, 100);}, function(errorResponse){ alert(errorResponse.error.message);});