java - 在 angularJS 中下载本地文件

标签 java angularjs spring pdf

我有一个适用于 Java 和 AngularJS 的应用程序。

我使用 Java 创建 pdf 文件,并使用 FileOutputStream 来存储它们:

        @RequestMapping(value = "/getPdf",
                method = RequestMethod.GET)
        @RolesAllowed(AuthoritiesConstants.USER)
        public List<String> getPdf(@RequestParam(value = "id") Long id){
                FileOutputStream fileStream = null;
                String fileName = textRepository.findOne(id).getTitle() + ".pdf";
                String text = textRepository.findOne(id).getUserText();
                try {
                    fileStream = new FileOutputStream(fileName);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // create an API client instance
                Client client = new Client("", "");
                client.convertHtml(text, fileName);

                try {
                    fileStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                List<String> out = new ArrayList<>();
                out.add(fileName);
                return out;
        }

 They are created in the root directory of my application.

现在我想实现一项功能,让用户通过单击链接或按钮来下载 pdf。我尝试过使用 $window.open(),但无法获取 pdf 文件的路径。

     $scope.getPdf = function (id) {
                TextService.getPdf(id).success(function(data){
                      $window.open('../../../../../../' + data[0], '_blank', 'download');
                });

            };

Here i get an error saying that Cannot GET /data.pdf
<小时/>

编辑 - 解决了问题

我必须执行一个POST方法来发送文件:

    @RequestMapping(value = "/getPdf",
            method = RequestMethod.POST)
    @RolesAllowed(AuthoritiesConstants.USER)
    public ResponseEntity<byte[]> getPdf(@RequestBody Long id){
        String filename = textRepository.findOne(id).getTitle() + ".pdf";
        String text = textRepository.findOne(id).getUserText();
        ByteArrayOutputStream pdf  = new ByteArrayOutputStream();

       // create an API client instance
        Client client = new Client("", "");
        client.convertHtml(text, pdf);

        byte[] content = pdf.toByteArray();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/pdf"));
        headers.setContentDispositionFormData("inline", filename);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = new ResponseEntity<>(content, headers, HttpStatus.OK);
        return response;

    }

回到我的 AngularJS 客户端,我有一个调用 Java 方法的服务:

angular.module("eddieApp")
    .factory("TextService", function($http){
        return{
            getPdf: function(id){
                return $http.post('texts/getPdf', id, { responseType: 'arraybuffer' });
            }
        };
    });

现在在 Controller 中我所要做的就是调用服务并打开一个包含 pdf 的窗口:

$scope.getPdf = function (id) {
            TextService.getPdf(id).success(function(data){
                var file = new Blob([data], {type: 'application/pdf'});
                var fileURL = ($window.URL || $window.webkitURL).createObjectURL(file);
                $window.open(fileURL, '_blank', 'download');
            });

        };

希望它能帮助别人!

最佳答案

如果您从网络服务器提供 Angular 部分,则无法访问服务器的文件系统。这将是一个严重的安全问题。

为什么不提供另一个 @RequestMapping(value = "/getFile") 来直接向用户提供文件,并使用正确的 MIME 类型?

这是一个类似的问题Return generated pdf using spring MVC以及如何做到这一点的答案。

关于java - 在 angularJS 中下载本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29683320/

相关文章:

java - Spring:如何使过滤器抛出自定义异常?

Java:函数可以返回调用类和方法名称的任何简单方法?

java - LocalDateTime JPA - Java 8

java - JdbcTemplate可以共享公共(public)事务吗?

javascript - 如何从深度嵌套的 ng-repeats 内的范围访问某些内容

java - Primefaces 日历 - 未显示正确的日期

java - ClassCastException InjectedDataSourceConnectionProvider Spring 3.1.0、Hibernate 4、JPA EntityManagerFactory

java - 如何使用项目默认 yaml 配置消息传递 activemq -thorntail 或 swarm

javascript - 从服务器端获取所有数据后计算数据并渲染它们; $(window).load() 没有运气

javascript - 使用 Gulp 时 AngularJS 组件配置错误