angularjs - Angular http get,从 spring mvc 服务器下载文件

标签 angularjs spring-mvc

我正在使用 apache commons IOUtils 复制方法将文件从服务器发送到 angularjs。 这是我的 Controller :

    @RequestMapping(value="/download", method = RequestMethod.GET)
    public void downloadFile(HttpServletResponse response) {

        response.setContentType("image/jpg");

        try {
            File file = new File(filePath);

            InputStream inputStream = new FileInputStream(file);
            IOUtils.copy(inputStream, response.getOutputStream());

        } catch (...) {
        .......
    }

在 angularJs Controller 中:

$http({

            method: 'GET',
            url: '.../download',
            headers: {'Content-Type': 'image/jpg'}

        })

        .success(function(data, status){

            console.log(data);
            var blob = new Blob([data], {type: 'image/jpg'});
            saveAs(blob, 'test.jpg');
        })

        .error(function(data, status){
            ....
        })

当我在客户端下载文件时,我无法读取它。当我用notepad++打开它时,我发现特殊字符被修改了。

例如,当我用 Notpad++ 打开原始文件时,我得到这样一行: òŽsCJVäl·²HWf…;¹(òÈ$ÓÒ«Á´{S€~9ÎsŠÒogk

同一行,当我用 Notepad++ 打开下载的文件时变成: ��sCJV�l��HW��;�(��$�ׁ����{S�~9�s�ogk

但是,当我将下载链接(localhost/myApplication/download)直接放入浏览器中时,它可以正常工作。文件应该被加密并且下载文件需要授权,所以我必须使用 Angular HTTP get。

如有任何帮助,我们将不胜感激。

最佳答案

我必须将responseType 添加到HTTP get 请求:

$http({

        method: 'GET',
        url: '.../download',
        responseType: 'arraybuffer'
    })

    .success(function(data, status){

        console.log(data);
        var blob = new Blob([data], {type: 'image/jpg'});
        saveAs(blob, 'test.jpg');
    })

    .error(function(data, status){
        ....
    })

现在它正在工作。

关于angularjs - Angular http get,从 spring mvc 服务器下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31690293/

相关文章:

javascript - 使用参数缓存 URL View /状态

javascript - 计算一个值在数组中出现的次数 - javascript - Angular - lodash

java - Spring bean Autowiring 不起作用

java - Spring、Hibernate、JUnit 带注释的实体

java - Spring 4 - 资源映射 - 未找到处理程序方法

javascript - 如何禁用 Angular 选择 View ?

javascript - 使用 AngularJS 使用 $http 发布到服务器

C# Protractor - 在另一个元素中查找元素

java - bean 类的完全限定名称,除非它仅用作子 bean 定义的父定义

java - spring和hibernate项目报错