从Spring服务器获取excel文件

时间:2017-08-06 10:02:21

标签: angularjs spring client-server

现在真的不知道该做什么。

我在我的服务器x​​ls文件上,我不会从我的客户端下载它。

我实际上是这样做的,但文件进入了一些奇怪的语言并完全破碎了。

客户:angular

服务器:spring 4

代码

客户端

function getXCEL() {
        self.onXCELProcess = true;
        AdminService.getXL(MotherService.getAppMember())
            .then(
                function (response) {

                    var file = new Blob([response], {type: 'application/excel'});

                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;

                    if (isChrome){
                        var url = window.URL || window.webkitURL;

                        var downloadLink = angular.element('<a></a>');
                        downloadLink.attr('href',url.createObjectURL(file));
                        downloadLink.attr('target','_self');
                        downloadLink.attr('download', 'yourReports.xls');
                        downloadLink[0].click();
                    }
                    else if(isEdge || isIE){
                        window.navigator.msSaveOrOpenBlob(file,'yourReports.xls');

                    }
                    else {
                        var fileURL = URL.createObjectURL(file);
                        window.open(fileURL);
                    }

                    self.onXCELProcess = false;
                },
                function (error) {
                    console.error("error : "+error+" , error : "+JSON.stringify(error));
                    self.onXCELProcess = false;
                }
            )
    }






function getXL(admin) {
        return MotherService.callToServer({method: 'POST', url: URL + "orderxl", appMember: admin});
    }

callToServer()方法请求,使用json正文。并返回deferred.promise 使用then

服务器

@RequestMapping(value = "/"+Request.ADMIN_PATH+"/"+Request.ORDER_XL, method = RequestMethod.POST)
    public void getFile(@RequestBody OrderXLRequest request, HttpServletResponse response) {
        try {
            File file = orderXLService.execute(request).getFile(); //get the file. already saved and ready to send

            try{
                InputStream inputStream = new FileInputStream(file);
                String headerKey = "Content-Disposition";
                String headerValue = String.format("attachment; filename=\"%s\"", "excelfilename.xlsx");
                response.setHeader(headerKey, headerValue);

                try {
                    FileCopyUtils.copy(inputStream, response.getOutputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }catch(Exception e){
                System.out.println("Exception in file download :"+e);
            }


        }catch (Exception e) {
            e.printStackTrace();
        }

    }

非常感谢您的任何帮助或建议

0 个答案:

没有答案