Rat
Rat

Reputation: 367

Return xml file from spring MVC controller

I have tried a lot to return a file from the 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:

Could not write JSON:
No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
(through reference chain:
org.springframework.core.io.FileSystemResource[\"outputStream\"]->java.io.FileOutputStream[\"fd\"]);
nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
(through reference chain: org.springframework.core.io.FileSystemResource[\"outputStream\"]->java.io.FileOutputStream[\"fd\"])

Does anyone have an idea how to solve it?

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

Upvotes: 7

Views: 10691

Answers (1)

MichaelCleverly
MichaelCleverly

Reputation: 2553

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 
}

Upvotes: 7

Related Questions