I have tried a lot to return a file from the controller function.
This is my function:
@RequestMapping(value = \"/files\", method = RequestMethod.GE
EDIT 2: First of all - see edit 1 in the bottom - that't the right way to do it. However, if you can't get your serializer to work, you can use this solution, where you read the XML file into a string, and promts the user to save it:
@RequestMapping(value = "/files", method = RequestMethod.GET)
public void saveTxtFile(HttpServletResponse response) throws IOException {
String yourXmlFileInAString;
response.setContentType("application/xml");
response.setHeader("Content-Disposition", "attachment;filename=thisIsTheFileName.xml");
BufferedReader br = new BufferedReader(new FileReader(new File(YourFile.xml)));
String line;
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!= null){
sb.append(line);
}
yourXmlFileInAString = sb.toString();
ServletOutputStream outStream = response.getOutputStream();
outStream.println(yourXmlFileInAString);
outStream.flush();
outStream.close();
}
That should do the job. Remember, however, that the browser caches URL contents - so it might be a good idea to use a unique URL per file.
EDIT:
After further examination, you should also just be able to add the following piece of code to your Action, to make it work:
response.setContentType("text/plain");
(Or for XML)
response.setContentType("application/xml");
So your complete solution should be:
@RequestMapping(value = "/files", method = RequestMethod.GET)
@ResponseBody public FileSystemResource getFile(HttpServletResponse response) {
response.setContentType("application/xml");
return new FileSystemResource(new File("try.xml")); //Or path to your file
}