1

The server response data like this: code screenshot

My angular code:

$scope.export = function() {
    var datas = new Blob([data], { type: 'application/vnd.ms-excel;charset=UTF-8' });
    FileSaver.saveAs(datas, '2016-04-20.xlsx');
}

And Header:

Accept-Range:bytes
Connection:keep-alive
Content-Disposition:attachment; filename=%E8%A1%A5%E8%B4%B4%E8%B5%84%E6%A0%BC%E5%B7%B2%E5%AE%A1%E6%A0%B8%E4%BF%A1%E6%81%AF%E8%A1%A8.xlsx
Date:Tue, 19 Apr 2016 17:23:06 GMT
Transfer-Encoding:chunked
X-Powered-By:Express

Dependencies Angular, FileSaver.js, Blob.js

But i got a wrong file, and can not open, how can i fixed this problem? Thanks!

Musa
  • 96,336
  • 17
  • 118
  • 137
Tammeny
  • 11
  • 1
  • 5

1 Answers1

3

I had a similar issue. I was able to get a valid file from third tools such as Postman, but not from own my code.

I figured that I forgot to set the responseType to blob on my HTTP request. This seems to be required in order to read binary data correctly.

Example:

$http({
    url: 'your/webservice',
    method: "POST",
    data: json, //this is your json data string
    headers: {
       'Content-type': 'application/json'
    },
    responseType: 'blob'
}).success(function (data, status, headers, config) {
    var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
    var objectUrl = URL.createObjectURL(blob);
    window.open(objectUrl);
}).error(function (data, status, headers, config) {
    //upload failed
});

The code comes from this answer.

Community
  • 1
  • 1
Andrew
  • 7,848
  • 1
  • 26
  • 24