我用Angular JS创建了一个应用程序,用于通过$http post下载Excel工作簿.

In the below code I'm passing the information in the form of JSON , and send it to the server REST web service (java) through an angular $http post. The web service uses the information from the JSON and produces an Excel workbook. In the response within the success body of $http post, I'm getting binary data within that data variable, but don't know how to convert it and download as an Excel file.

谁能告诉我一些将二进制文件转换成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, status, headers, config) {

    });

推荐答案

Just noticed you can't use it because of IE8/9 but I'll push submit anyway... maybe someone finds it useful

这实际上可以通过浏览器来完成,使用blob.注意responseTypesuccesspromise 中的代码.

$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
});

不过,它也存在一些问题,比如:

  1. 它不支持IE 8 and 9:
  2. It opens a pop up window to open the objectUrl which people might have blocked
  3. 生成奇怪的文件名

It did work!

blob

$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));

Edit 20.04.2016

Browsers are making it harder to save data this way. One good option is to use filesaver.js. It provides a cross browser implementation for saveAs, and it should replace some of the code in the success promise above.

Json相关问答推荐

try 将文本标记放置在条形图上的同一高度

使用Jolt将字符串数组转换为JSON对象数组

报告重复的对象键

使用Powershell将JSON文件加载到SQL Server表格

从 Inno Setup 中的 JSON 文件的每个对象中读取特定字符串

如何从 json 中获取单个元素?

如何在 Android Studio 中将 List 字段作为空列表[]返回?

使用 ConvertFrom-Json 后,Powershell 访问 JSON 中的嵌套对象

Go - JSON 验证抛出错误,除非我在 struct 中使用指针.为什么?

使用 JQ 从文件中删除重复的 JSON 块

在 Flutter 中将对象转换为可编码对象失败

JQuery,使用 GET 方法发送 JSON 对象

JBuilder中未定义的局部变量或方法json

单元测试球衣 Restful Services

Retrofit 2.0 如何解析嵌套的 JSON 对象?

Laravel5 Json 获取文件内容

在 JSON 对象中强制执行非空字段

SCRIPT5009:JSON未定义

FastAPI:如何将正文读取为任何有效的 json?

使用 jQuery 和 JSON 填充表单?