Reputation: 1420
I am trying to read ByteArray to show PDF form Java into Angular JS using
method : 'GET'
url : '',
cache : isCache||false,
responseType: 'arraybuffer'
This is working fine when everything okay.
But when I throw an exception with some proper JSON and marking HTTP Status as bad request, I can't read JSON response even after changing config to respone.config.responseType='application/json'.
It showing only empty ArrayBuffer {}
on response.data.
But important thing here is, I can see JSON response in google chrome developer tool request.
I googled, searched on stack overflow but didn't find much.
Below lines added later
I am adding response object picture and data received pic from chrome network connection.
First Image : Response object from error function of angular JS.
Second Image - Server returning proper JSON message
Third Image - Request and Response Header pics
Only problem I am facing is not able read data of response as I set response type to arraybuffer
Upvotes: 3
Views: 2944
Reputation: 338
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
Upvotes: 1
Reputation: 810
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);
});
Upvotes: -1