4

I'd like to download a protected file from my backed - I have to send authorization headers, so I can't link it directly. I have created following Ajax request to download it:

Ember.$.ajax({
     url: self.get("file.filepath"),
     type: "GET",
     beforeSend: function(xhr) {
        xhr.setRequestHeader(header, content);
     },
     processData: false,
     success: function (result, a, xhr) {
         var blob = new Blob([result], {type: xhr.getResponseHeader("content-type") || ""});
         saveAs(blob, self.get("file.filename"));
     }
});

Everything works fine when dealing with text files. However when I try to download binary file (image), I get complete nonsence (even the binary string in response printed via console seems fine to me). So I suppose there's a problem in blob construction.

I have tried to use Int8Array, however it didn't helped. What am I doing wrong?

yaqwsx
  • 569
  • 1
  • 5
  • 14
  • 4
    Try using `XMLHttpRequest` with `responseType` set to `"blob"` , `URL.createObjectURL()` , see http://stackoverflow.com/questions/12876000/how-to-build-pdf-file-from-binary-string-returned-from-a-web-service-using-javas – guest271314 Nov 09 '15 at 22:59
  • Thanks a lot - this works! – yaqwsx Nov 10 '15 at 09:08

2 Answers2

0

I had today the same issue that's an angular code, but maybe something will help you from it

return $http({
    url: host + "api/map/rectangleMap",
    method: 'POST',
    data: angular.toJson(coords),
    responseType: 'blob',
    transformResponse: function(data){
        return new Blob([data], {type: 'image/png'});
    }
});
Danil Gudz
  • 2,233
  • 16
  • 16
0

There is a correct answer in guest271314's answer - link to solution. It is the only working solution I was able to find.

Community
  • 1
  • 1
yaqwsx
  • 569
  • 1
  • 5
  • 14