使用AngularJS从服务器下载和保存文件

8

我遇到了以下问题,但是找不到解决方法。我使用Spring Boot创建了端点,在使用Postman时,响应主体中包含图像。

但是,当我尝试使用Angular、Blob和FileSaver下载并保存文件到计算机时,我的保存文件无法读取。

这是我的Angular控制器:

vm.download = function (filename) {
    console.log("Start download. File name:", filename);
    $http.get('api/files/download/' + filename)
        .then(function (response) {
            console.log(data);
            var data = new Blob([response.data], {type: 'image/jpeg;charset=UTF-8'});
            FileSaver.saveAs(data, filename);
        })
}

以下是我的端点:

@RequestMapping(value = "/files/download/{id:.*}", method = RequestMethod.GET)
@ResponseBody
@Timed
public void DownloadFiles(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {

    MongoClient mongoClient = new MongoClient();
    DB mongoDB = mongoClient.getDB("angularspingproject");


    BasicDBObject query = new BasicDBObject();
    query.put("filename", id);

    GridFS fileStore = new GridFS(mongoDB, "fs");
    GridFSDBFile gridFSDBFile = fileStore.findOne(query);

    if (gridFSDBFile != null && id.equalsIgnoreCase((String) gridFSDBFile.getFilename())) {
        try {
            response.setContentType(gridFSDBFile.getContentType());
            response.setContentLength((new Long(gridFSDBFile.getLength()).intValue()));
            response.setHeader("content-Disposition", "attachment; filename=" + gridFSDBFile.getFilename());

            IOUtils.copyLarge(gridFSDBFile.getInputStream(), response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("IOError writting file to output stream");
        }
    }
}

我的标题:

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 316707
Content-Type: image/jpeg;charset=UTF-8
Pragma: no-cache
Server:Apache-Coyote/1.1
X-Application-Context : angularspingproject:8080
X-Content-Type-Options : nosniff
X-XSS-Protection: 1; mode=block
content-Disposition: attachment; filename=main_page.jpg

@编辑 问题已解决

    vm.download = function (filename) {
        $http.get('api/files/download/' + filename, {responseType:'blob'})
            .then(function (response) {
                console.log(response);
                var data = new Blob([response.data], {type: 'image/jpeg;charset=UTF-8'});
                FileSaver.saveAs(data, filename);
            })
    }

我在 $http 中添加了 responseType: 'blob'。
2个回答

1
我猜测您的 $http.get 调用没有返回字节数组。尝试添加以下内容:
vm.download = function (filename) {
var config = {headers: {
        'Accept': "image/jpeg"
    }
};
$http.get('api/files/download/' + filename, config).then(function (response)             { 
       var myBuffer= new Uint8Array( response.data );

    var data = new Blob([myBuffer], {type: 'image/jpeg;charset=UTF-8'});
    FileSaver.saveAs(data, filename);
        })
}

很遗憾,它没有帮助。 - Michał Styś
我刚刚修改了它。我原本使用的是png而不是jpeg。这可能是问题所在。 - Mike Feltman
我刚刚添加了创建数组缓冲区的代码。这正是构造函数中 Blob 需要的。 - Mike Feltman

0

我在Angular中有一个特殊的下载服务,非常好用和简单:

(function () {
    angular.module('common')
        .factory('downloadService', ['$http', '$window', 'contentDispositionParser',
            function ($http, $window, contentDispositionParser) {
                return {
                    downloadFile: downloadFile
                };

                function downloadFile(url, request)
                {
                    $http({
                        url: url, 
                        method: 'GET',
                        params: request,
                        responseType: 'blob'
                    })
                    .success(function (data, status, headers, config){
                        var disposition = headers('Content-Disposition');
                        var filename = contentDispositionParser.getFileName(disposition);
                        $window.saveAs(data, filename); // This is from FileSaver.js
                    });
                }

            }]);
})();

Filesaver.js 可以从 这里 下载。 ContentDispositionParser 可以使用任何方法或自己编写,它仅用于获取正确的文件名,因为这显然不是一项容易的任务,但与保存文件本身没有直接关联(您可以在 js 中添加名称等)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接