Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular http get, download file from spring mvc server

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.

like image 992
Bilal BBB Avatar asked Dec 21 '25 20:12

Bilal BBB


1 Answers

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.

like image 141
Bilal BBB Avatar answered Dec 24 '25 00:12

Bilal BBB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!