Search code examples
javascriptajaxbin

Image size (.bin) getting doubled while generating it via AJAX call


I am trying to generate .bin file from from REST API written in Swing from AngularJS.Following is the code.

var options = {
  url: 'http://example.com/imageAPI',
  method: 'POST',
  headers: {
    'Authentication': headerAndPostParams[0],
    'Content-Type': 'application/json',
    'Accept': 'application/octet-stream'
  },
  responseType: 'arraybuffer',
  data: {
    uniqueId: headerAndPostParams[1],
    imageName: headerAndPostParams[2],
    clientMacAddress: headerAndPostParams[3]
  }
};
return $http(options).then(function(sucessResponse) {
  if (sucessResponse.data != "" && sucessResponse.data.responseCode === undefined) {
    download(sucessResponse.data, "image.bin", "application/octet-stream");
    return true;
  }
  return false;
});

Here are the response headers
Access-Control-Allow-Origin: http://localhost:8080
Content-Disposition:attachment;filename=cns3xxx_md_2.6.9_ac_aa_33_dd_aa_35.bin
Content-Length :7864320
Content-Type :application/octet-stream
Date :Tue, 18 Apr 2017 06:38:35 GMT
Vary :Origin
access-control-allow-credentials: true
Above code is working fine.But the issue is Image sent from API is of size 7.5 MB and the image generated from my UI side is of size 13.5 MB. Is there any decoding that we have to perform before giving it to donwload function.
(NOTE: download is the function from donwload.js library.)


Solution

  • Found the solution. Actually $http service by default change the response to text. That doubles the size of image. To avoid it we need to add following parameter.

    responseType: "blob"

    $http({
      url: 'http://example.com',
      method: 'POST',
      responseType: "blob",
      headers: {
        'Authentication': headerAndPostParams[0],
        'Content-Type': 'application/json',
        'Accept': 'application/octet-stream'
      },
      data: {
        uniqueId: headerAndPostParams[1],
        imageName: headerAndPostParams[2],
        clientMacAddress: headerAndPostParams[3]
      }
    }).then(function(sucessResponse) {
      if (sucessResponse.data != "" && sucessResponse.data.responseCode === undefined) {
        var blob = new Blob([sucessResponse.data], {
          type: "application/octet-stream"
        });
        download(blob, headerAndPostParams[2]);
        return true;
      }
      return false;
    }, function(response) {
      return false;
    });