2

I am using angular $http to download file from server. file types can be different. I should set request header in order to authentication. when download finishes, file is corrupted! here is my code in client side to save the file:

getFile: function(file) {
    $http({
        method: 'GET',
        url: 'download' + "/" + file.name,
        headers: {
            "X-AUTH-TOKEN": "my-token",
            Accept: "*/*",
        }
    }).success(function(data) {
        var fileBlob = new Blob([data], {
            type: '*/*;charset=utf-8'
        });
        saveAs(fileBlob, file.name);
    }).error(function(err) {
        console.log('err', err);
    });
}
MortenMoulder
  • 6,138
  • 11
  • 60
  • 116
Hadi Ranjbar
  • 1,692
  • 4
  • 21
  • 44
  • is your corrupted file a binary file or text file? – Jean-François Fabre Aug 13 '16 at 20:23
  • *.txt files are OK. but *.pdf, *.docx, etc are corrupted – Hadi Ranjbar Aug 13 '16 at 20:40
  • Saving a binary file as a text file results in lots of characters being interpreted, thus corrupting the binary file. I have deleted my answer since it doesn't cut it, but that's probably the reason. Dig further here: http://stackoverflow.com/questions/23451726/saving-binary-data-as-file-using-javascript-from-a-browser – Jean-François Fabre Aug 13 '16 at 21:18

1 Answers1

9

I finally solved it by adding this configs to ajax request:

    dataType : "binary",
    processData : false,
    responseType : 'arraybuffer'

and changing blob type to

"application/octet-stream"

Hadi Ranjbar
  • 1,692
  • 4
  • 21
  • 44
  • can anyone help me out with this? http://stackoverflow.com/questions/42396959/downloaded-document-getting-corrupted-using-blob-method-in-angularjs – Phoenix Feb 22 '17 at 16:45