AngularJS $ http-post - 将二进制文件转换为excel文件并下载

Ale*_*Man 52 excel json http-post angularjs

我在Angular JS中创建了一个应用程序,用于通过$ http帖子下载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, status, headers, config) {

    });
Run Code Online (Sandbox Code Playgroud)

Jor*_*org 79

刚注意到你因为IE8/9而无法使用它,但无论如何我都会推送提交...也许有人发现它很有用

这实际上可以通过浏览器来完成blob.注意承诺中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
});
Run Code Online (Sandbox Code Playgroud)

它有一些问题,但是:

  1. 它不支持IE 8和9:
  2. 它会打开一个弹出窗口,打开objectUrl人们可能已阻止的窗口
  3. 生成奇怪的文件名

它确实有效!

BLOB 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));
Run Code Online (Sandbox Code Playgroud)

编辑20.04.2016

浏览器使得以这种方式保存数据变得更加困难.一个不错的选择是使用filesaver.js.它提供了一个跨浏览器实现saveAs,它应该替换success上面的promise 中的一些代码.

  • 优秀!**`responseType:'arraybuffer'是我的关键**.我不得不与[connect-livereload问题导致zip文件损坏]作斗争(http://stackoverflow.com/questions/29562954/downloaded-pdf-files-are-corrupted-when-using-expressjs?answertab=active#tab-顶部)在服务器上,所以这个角度调整是更快找到欢迎修复!谢谢! (5认同)

Edu*_*way 24

这是你如何做到的:

  1. 忘记IE8/IE9,它不值得努力,不付钱.
  2. 您需要使用正确的HTTP标头,使用Accept to'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',并且还需要将responseType放入'arraybuffer'(ArrayBuffer,但设置为小写).
  3. HTML5 saveAs用于将实际数据保存为您想要的格式.请注意,在这种情况下,它仍然可以在不添加类型的情
$http({
    url: 'your/webservice',
    method: 'POST',
    responseType: 'arraybuffer',
    data: json, //this is your json data string
    headers: {
        'Content-type': 'application/json',
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }
}).success(function(data){
    var blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    saveAs(blob, 'File_Name_With_Some_Unique_Id_Time' + '.xlsx');
}).error(function(){
    //Some error log
});
Run Code Online (Sandbox Code Playgroud)

小费!不要混合"和',坚持使用',在专业环境中你必须通过js验证例如jshint,同样适用于使用===而不是==,等等,但这是另一个话题:)

我会将save excel放在另一个服务中,所以你有一个干净的结构,帖子是自己的适当服务.如果你没有让我的榜样有效,我可以为你制作一个JS小提琴.然后我还需要你使用的一些json数据作为完整的例子.

快乐的编码..爱德华多

  • 从我工作..但依赖于http://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js FileSaver for saveAs (6认同)

Edw*_*rey 10

将服务器响应下载为阵列缓冲区.使用服务器中的内容类型(应该是application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)将其存储为Blob :

var httpPromise = this.$http.post(server, postData, { responseType: 'arraybuffer' });
httpPromise.then(response => this.save(new Blob([response.data],
    { type: response.headers('Content-Type') }), fileName));
Run Code Online (Sandbox Code Playgroud)

将blob保存到用户的设备:

save(blob, fileName) {
    if (window.navigator.msSaveOrOpenBlob) { // For IE:
        navigator.msSaveBlob(blob, fileName);
    } else { // For other browsers:
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

为我工作 -

$scope.downloadFile = function () {
        Resource.downloadFile().then(function (response) {
            var blob = new Blob([response.data], { type: "application/pdf" });
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);
        },
        function (error) {
            debugger;
        });
    };
Run Code Online (Sandbox Code Playgroud)

从我的资源工厂调用以下内容 -

  downloadFile: function () {
           var downloadRequst = {
                method: 'GET',
                url: 'http://localhost/api/downloadFile?fileId=dfckn4niudsifdh.pdf',
                headers: {
                    'Content-Type': "application/pdf",
                    'Accept': "application/pdf"
                },
                responseType: 'arraybuffer'
            }

            return $http(downloadRequst);
        }
Run Code Online (Sandbox Code Playgroud)

确保您的API也设置了标题内容类型 -

        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
Run Code Online (Sandbox Code Playgroud)