I have an Angular 1.x application that is expecting to receive a binary file download (pdf) using a $http.post()
call. The problem is, I\'d like to alternative
An XHR responseType
property can not be changed after a response has been loaded. But an arraybuffer
can be decoded and parsed depending on Content-Type
:
var config = {
responseType: "arraybuffer",
transformResponse: jsonBufferToObject,
};
function jsonBufferToObject (data, headersGetter, status) {
var type = headersGetter("Content-Type");
if (!type.startsWith("application/json")) {
return data;
};
var decoder = new TextDecoder("utf-8");
var domString = decoder.decode(data);
var json = JSON.parse(domString);
return json;
};
$http.get(url, config);
The above example sets the XHR to return an arraybuffer
and uses a transformResponse
function to detect Content-Type: application/json
and convert it if necessary.
The DEMO on PLNKR