如何解决AngularJS $http-post - 将二进制文件转换为 excel 文件并下载
只是注意到由于 IE8/9 而无法使用它,但我还是会推送提交……也许有人觉得它有用
这实际上可以通过浏览器完成,使用blob
. 注意 Promise 中的responseType
和 代码success
。
$http({
url: 'your/webservice',
method: "POST",
data: json, //this is your json data string
headers: {
'Content-type': 'application/json'
},
responseType: 'arraybuffer'
}).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
});
虽然它存在一些问题,例如:
- 它不支持IE 8 和 9:
- 它会打开一个弹出窗口以打开
objectUrl
可能被阻止的人 - 生成奇怪的文件名
它确实奏效了!
我测试过的 PHP 中的服务器端代码如下所示。我确定您可以在 Java 中设置类似的标头:
$file = "file.xlsx";
header('Content-disposition: attachment; filename='.$file);
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
echo json_encode(readfile($file));
编辑 20.04.2016
浏览器使以这种方式保存数据变得更加困难。一个不错的选择是使用filesaver.js。它为 提供了一个跨浏览器的实现saveAs
,它应该替换success
上面 Promise 中的一些代码。
解决方法
我在 Angular JS 中创建了一个应用程序,用于通过 $http post 下载 Excel 工作簿。
在下面的代码中,我以 JSON 的形式传递信息,并通过有角度的 $http 帖子将其发送到服务器 REST Web 服务 (java)。Web 服务使用来自 JSON 的信息并生成 Excel 工作簿。在 $http post 的成功正文中的响应中,我在该数据变量中获取二进制数据,但不知道如何将其转换并下载为 Excel 文件。
谁能告诉我一些将二进制文件转换为 Excel 文件并下载的解决方案?
我的代码如下所示:
$http({
url: 'myweb.com/myrestService',method: "POST",data: json,//this is your json data string
headers: {
'Content-type': 'application/json'
}
}).success(function (data,status,headers,config) {
// Here i'm getting excel sheet binary datas in 'data'
}).error(function (data,config) {
});