angular http get, download file from spring mvc se

2020-04-10 01:26发布

I'm using apache commons IOUtils copy method to send file from server to angularjs. This is my 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 (...) {
        .......
    }

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

When I download the file in the client side, I can't read it. When I open it with notepad++ I find that special characters are modified.

For example, when I open the original file with Notpad++, I get a line like this : òŽsCJVäl·²HWƒ…;¹(òÈ$ÓÒ«Á‘{S€~9ÎsŠÒogk

The same line, when I open the downloaded file with notepad++ becomes : ��sCJV�l��HW��;�(��$�Ӂҫ��{S�~9�s��ogk

However, when I put the download link (localhost/myApplication/download) directly in a browser, it works correctly. Files are supposed to be encrypted and authorization is needed to download a file, so I have to use angular HTTP get.

Any help would be appreciated.

1条回答
倾城 Initia
2楼-- · 2020-04-10 01:48

I had to add responseType to 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){
        ....
    })

Now it is working.

查看更多
登录 后发表回答