How to read JSON error response from $http if responseType is arraybuffer

前端 未结 3 1247
别跟我提以往
别跟我提以往 2020-12-08 09:22

I load some binary data using

$http.post(url, data, { responseType: \"arraybuffer\" }).success(
            function (data) { /*  */ });

I

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 09:53

    @smkanadl's answer assumes that the response is ASCII. If your response is in another encoding, then that won't work.

    Modern browsers (eg. FF and Chrome, but not IE yet) now support the TextDecoder interface that allows you to decode a string from an ArrayBuffer (via a DataView).

    if ('TextDecoder' in window) {
      // Decode as UTF-8
      var dataView = new DataView(data);
      var decoder = new TextDecoder('utf8');
      var response = JSON.parse(decoder.decode(dataView));
    } else {
      // Fallback decode as ASCII
      var decodedString = String.fromCharCode.apply(null, new Uint8Array(data));
      var response = JSON.parse(decodedString);
    }
    

提交回复
热议问题