角http获取,从Spring MVC服务器下载文件


问题内容

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

    @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控制器中:

$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){
            ....
        })

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

例如,当我使用Notpad ++打开原始文件时,将得到如下代码:òŽsCJVäl·²HWƒ…;¹(òÈ$ÓÒ«ÁÂ’{ S€~9ÎsŠÒogk

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

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

任何帮助,将不胜感激。


问题答案:

我必须将responseType添加到HTTP get request中:

$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){
        ....
    })

现在正在工作。