0

I have a Spring Controller which send file in response

@RequestMapping(value = "/downloadData", method = RequestMethod.GET)
public void downloadData(HttpServletResponse response) throws IOException
{
    File dataJSONFile = dataDownloadService.createAndWriteFile();
    response.setContentType("application/text");
    response.setContentLength(new Long(dataJSONFile.length()).intValue());
    response.setHeader("Content-Disposition", "attachment; filename="data.json");
    FileCopyUtils.copy(new FileInputStream(dataJSONFile),     
    response.getOutputStream());
}

If I write in browser url, //localhost:8080/myproject/rest/downloadData It downloads the file.

Now, want to download the file when click on button in using angular js.

I have written following code in angular js to download file

angular
    .module('myApp.services')
    .factory(
            'DataDownloadService',
            function($resource) {
                "use strict";
                return {
                    "query" : function() {
                        var ret, restResource;
                        restResource = $resource(
                                '/sand-pp/api/rest/downloadData',
                                {}, {
                                    "query" : {
                                        "method" : "GET",
                                        "isArray" : true,
                                        headers:
                                        {
                                            'Content-Type': 'application/text',
                                            'Content-Disposition': 'attachment; filename=data.json'

                                        }
                                    }
                                });
                        ret = restResource.query();
                        return ret;
                    }
                };
            });

When I call above service nothing is happening but if I print data in callback function is printing data in console. How to download file in angular js by calling Spring REST api?

1 Answer 1

0

I would use a service for the rest call. Try this following:

window.location.href = DataDownloadService.query();

It should prompt the browser to download the file (because of Content-Disposition header).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.