0

I want my web service to return a data file to the caller that they can save on their file system. The problem is that instead of displaying a popup to save the file, it gets displayed in the browser. The following code illustrates the problem:

@GetMapping(value = "/test", produces = "text/plain")
public void testDownload(HttpServletResponse response, Writer responseWriter) {
try {
    for (int i = 0; i < 10; i++) {
        responseWriter.write("Hello World, this is row " + i + "\n");
    }
    responseWriter.flush();
    responseWriter.close();
} catch (IOException e) {
    e.printStackTrace();
}
response.setContentType("text/txt");
response.setHeader("Content-Disposition", "attachment; filename=HelloWorld.txt");
}

Running this results in the returned ten lines being displayed in the browser. I assume I'm missing something in the response but I can't figure out what. The code shown above implements the accepted answer for this question regarding file download (i.e., use the outputStream, set the ContentType). That suffices to return the data to the caller but that isn't my problem. I need to ensure it doesn't get displayed in the browser but instead the user is prompted to save it.

LJ in NJ
  • 196
  • 1
  • 1
  • 12
  • 2
    Possible duplicate of [Downloading a file from spring controllers](https://stackoverflow.com/questions/5673260/downloading-a-file-from-spring-controllers) – tryingToLearn Mar 09 '18 at 07:40
  • I've edited the original question to clarify why this is not a duplicate of the "Downloading a file" question. – LJ in NJ Mar 09 '18 at 16:04

0 Answers0