![](/img/trans.png)
[英]How to download a binary file returned from HTTP:POST request via angular.js?
[英]How to convert the binary code from the rest api to a excel file in angular.js
我将文件内容作为二进制或字节数组(来自 REST API)获取,并希望将其转换为 excel 文件并使用 angular.js 在客户端下载它,但不知道该怎么做。 有人可以帮我从这里出去吗。
我还在此处附加了代码,正在下载 .xls 文件,但在打开它后,文件内容仍然是我从 api 响应中获取的相同二进制/字节内容,而不是实际的文件内容。 谁能告诉我在这里缺少什么。 或者我如何将响应转换/读取为实际格式。 非常感谢任何帮助,因为我完全卡住了。
$http.get(__env.apiUrl+"/UserSurvey/GetTrackingReport?surveyId="+$rootScope.surveysummaryID,{headers:{"Content-type":"application/json",'sessionID':$rootScope.token}}).then(function(response){
console.log(response);
var blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
if (window.navigator && window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob);
}
else {
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
},function(error){
console.log(error);
});
非常感谢,
如果有人遇到同样的问题,我就错过了 unsignedint 值的转换,并将其传递给 blob 对象,它可以工作!!
$http.get(__env.apiUrl+"/UserSurvey/GetTrackingReport?surveyId="+$rootScope.surveysummaryID,{headers:{"Content-type":"application/json",'sessionID':$rootScope.token,'Accept': "application/vnd.ms-excel"}}, {responseType: 'arraybuffer'}).then(function(response){
var dec = window.atob(response.data);
var myArr = new Uint8Array(dec.length)
for(var i = 0; i < Object.keys(dec).length; i++){
myArr[i] = dec.charCodeAt(i);
}
var blob = new Blob([myArr], {type: 'application/vnd.ms-excel'});
if (window.navigator && window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob);
}
else {
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
},function(error){
console.log(error);
});
希望这对某人有帮助!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.