最近在用anjular post请求导出excel遇到的一些问题

以往做过直接导出数据,和上传excel,
用的poi3.17,前端框架用的angular
之前在导出时,都可以生成我预设的文件名,文件格式与后缀的excel
之前导出使用的是这样的

window.location.href = "/api/livecoursepay?courseName=" + $scope.courseName + "&types=" + 14;

赋现在的post传值代码

$scope.uploadlineGuangdian=function(){
        var fd = new FormData();
        fd.append("file", $("#file")[0].files[0]);
        fd.append("types",1);


        $http.post("/api/improtExcel/guangdian",fd,{
            withCredentials: true,
            headers: {'Content-Type': undefined },
            responseType: 'arraybuffer',
            transformRequest: angular.identity
        })
        .success(function(data){
            var blob = new Blob([data], {type: "application/vnd.ms-excel"});
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);
        })
    }

但本次需求变更,需要导入一个excel文件,在返回一个excel文件,
所以只能用 post请求,但是使用过程中出现一些问题,
内容,表格名称都是我想要的样子,但是excel文件名和文件格式变成了奇怪的东西,
我需要用excel表格形式打开,再用excel另存才能达到我想要的样子
图片说明图片说明

用window.location.href走的话在页面下载的就是excel文件而且文件名是我设置好的文件名
但是用上面的post方法返回的是一个没有后缀名的,文件名是一排随机编码的文件,需要用excel打开(如上图),但是打开后数据是我想要的

所以我想问问大神为什么会出现这种情况,怎么解决,非常感谢

将success内替换成这样,问题解决,但原理还需要研究

var blob = new Blob([data], {type: "application/vnd.ms-excel"});

            let fileName = '证书信息.xls';

            const elink = document.createElement('a');

            elink.download = fileName;

            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);

            document.body.appendChild(elink);

            elink.click();

            URL.revokeObjectURL(elink.href); // 释放URL 对象

            document.body.removeChild(elink);

            loading.close(); 

原因很简单,因为你后台设置的文件名是放在response的head里面的,而你

            var blob = new Blob([data], {type: "application/vnd.ms-excel"});
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);

的操作,等于打开一个新网页只传了的文件的数据,而没有传文件名。

你之后的做法就是新建了一个元素,然后利用元素自带的download属性加上了文件名