javascript - 使用 Angular 从服务器下载文件

标签 javascript java angularjs spring model-view-controller

我想通过 REST 从服务器下载文件。我想将一些参数传递给我的 JAVA 程序。我发现 FileSaver.js 库运行良好,但不适用于 Safari 8。如何在 Safari 中下载文件?像这样的angular http get仅适用于 Google Chrome,我不知道如何将参数传递给 http get。我使用 JAVA 和 Spring MVC

最佳答案

在后端,我们像这样提供文件:

@RequestMapping(value = "/fileService/temp/{temporalLink}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getFileByTemporalLink(@PathVariable @NotNull String temporalLink) {

    byte[] fileContent; // get the file content somehow
    String fileName; // and file name
    String mediaType; // and media type

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(mediaType));
    headers.setContentDispositionFormData("attachment", fileName);
    return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
}

在前端我们这样要求:

以及内部 Controller :

 $scope.exportProductToPdf = function (someParams) {    
        getFileDownloadLink(someParams).then(function (response) {
                $window.location.href = '/fileService/temp/' + response;
            });
        };

//代码中的某处

var getFileDownloadLink = function(someParams) { 

     //we do some promise work here to determine what file is being asked
     // but basically we resolve the filename. 

    return $q(function(resolve, reject) {
        //some work here...
        resolve("filename.png");

    });

}

关于javascript - 使用 Angular 从服务器下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34423672/

相关文章:

javascript - Pinterest API : Cannot access 'Metadata' object property,,即使其他属性可访问

javascript - 如何以编程方式指定要在浏览器中打印的页面范围(使用 javascript 或 css)

javascript - 悬停后 vbox 关闭的 menupopup(Firefox 扩展)

javascript - 如何判断 dom-repeat 何时完成冲压元素

Java getClass().getClassLoader().getResource( "/My_Form.xsd") 返回 null

java - Spring Context 是否具有相当于 Java CDI 的 @Inject @Any

javascript - 滚动条在聊天框中不起作用?

java - 隐藏面板后空白区域仍然可见

javascript - 在 AngularJS 中使用 $window 或 $location 重定向

html - 将元素从一个多选列表新添加/删除到另一个时更改元素的背景颜色