使用angularjs向浏览器发送servlet响应(下载功能)

Send servlet response to browser using angularjs (DOWNLOAD FEATURE)

本文关键字:响应 下载 功能 servlet angularjs 浏览器 使用      更新时间:2023-09-26

我有一个NG-GRID,用于填充数据。用户选择一些行并尝试导出。在导出的报表中只能看到这些行。

我正在做的方法/设计是:

  1. 将选定的行值发送到服务器
  2. 被调用的servlet从客户端获取行信息,并处理XLS文件,作为响应,为要下载的文件添加文件和头的所有详细信息
  3. 调用servlet的函数返回接收到的数据。下面是ng-click()上调用的下载函数下载数据servlet正在创建文件,并在响应中写入文件和头的数据。

    $scope.download=函数(){$scope.downloadText="正在准备文档…";$scope.isDownloadDisabled=true;return($http.post('./DownloadData',mySelections).success(函数(数据、状态、标头、配置){$scope.downloadText="下载";$scope.isDownloadDisabled=false;console.log("我在这里")返回数据;}));}

但我没有看到数据被下载。尽管标题是正确的。

以下是在服务器上执行的功能代码:

private void processData(HttpServletRequest request, HttpServletResponse response) throws ServletException
    {
        try
        {
            Map<String, Map<String, String>> loadedData = getTableDataForRequest(request);
            if (loadedData == null || loadedData.size() == 0)
            {
                log.error("Exception no data generated for exporting");
                throw new ServletException();
            }
            else
            {
                XLSDataWriter xlsDataWriter = new XLSDataWriter(loadedData);
                String pathToGeneratedFile = getServletContext().getRealPath("resources");
                pathToGeneratedFile = pathToGeneratedFile.substring(0, pathToGeneratedFile.indexOf("resources"));
                pathToGeneratedFile += "generatedFiles" + File.separator;
                File file = xlsDataWriter.writeDataToXls(pathToGeneratedFile);
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition", "attachment; filename=" + file.getName());
                OutputStream outStream = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                FileInputStream inStream = new FileInputStream(file);
                while ((bytesRead = inStream.read(buffer)) != -1)
                {
                    outStream.write(buffer, 0, bytesRead);
                }
                inStream.close();
                log.info("Full file path : " + file.getAbsolutePath());
            }
        }
        catch (Exception ex)
        {
            log.error("Exception while fetching the download data", ex);
        }
    }

请帮帮我,我已经陷入困境很多天了。

好的,这是我为解决这个问题所做的。

创建了角度函数内部的链接。

将href属性分配给servlet,servlet通过传递myselection变量返回附件文件。

并执行了点击的操作。

$scope.downloadText="Downloading...";
        $scope.isDownloadDisabled=true;
        var servletPath = './DownloadData?JSON='+JSON.stringify(mySelections);
        var downloadLink = angular.element('<a></a>');
        downloadLink.attr('href',servletPath);
        downloadLink[0].click();
        $scope.downloadText="Download";
        $scope.isDownloadDisabled=false;