Return xml file from spring MVC controller

I've tried a lot to return a file from a controller function.

This is my function:

@RequestMapping(value = "/files", method = RequestMethod.GET)
@ResponseBody public FileSystemResource getFile() {
     return new FileSystemResource(new File("try.txt")); 
}

      

I got this error message:

Failed to write JSON:
Separator not found for class java.io.FileDescriptor and no properties found to create BeanSerializer
(disable SerializationFeature.FAIL_ON_EMPTY_BEANS to avoid exception)
(via link chain:
org.springframework.core.io.FileSystemResource [\ " OutputStream \ "] → java.io.FileOutputStream [\" FD \ "]);
Nested Exception - com.fasterxml.jackson.databind.JsonMappingException: Serializer not found for class java.io.FileDescriptor and no properties found to create BeanSerializer
(disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
(via link chain: org. core.io.FileSystemResource [\ "outputStream \"] → java.io.FileOutputStream [\ "fd \"])

Does anyone have any idea how to solve it?

And how do I send the client (JavaScript, jQuery)?

+3


source to share


1 answer


EDIT 2: First of all - see edit 1 below - this is the correct way to do it. However, if you cannot get your serializer to work, you can use this solution where you read the XML file into a string and forces 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();
}

      

This should do the job. Remember, however, that the browser caches the content of the URLs - so it would be a good idea to use a unique URL for each file.

EDIT:

After further exploring, you should simply add the following piece of code to your Action for it to 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 
}

      

+5


source







All Articles