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?

2
  • 4
    Try using XMLHttpRequest with responseType set to "blob" , URL.createObjectURL() , see stackoverflow.com/questions/12876000/… Commented Nov 9, 2015 at 22:59
  • Thanks a lot - this works! Commented Nov 10, 2015 at 9:08

2 Answers 2

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'});
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.