使用angular从服务器下载文件

Download file from server with angular

本文关键字:下载 文件 服务器 angular 使用      更新时间:2023-09-26

我想通过REST从服务器下载文件。我想用JAVA将一些参数传递给我的程序。我找到了FileSaver.js库,它很好用,但在Safari8中没有。如何在Safari中下载文件?像这种棱角分明的http-get只在GoogleChrome中工作,我不知道如何将参数传递给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);
}

在前端,我们这样要求:

内部控制器:

 $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");
    });

}