从spring MVC控制器返回xml文件

我已经尝试了很多从控制器函数返回文件。

这是我的function:

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

我收到此错误消息:

无法写JSON:
没有为类java.io.FileDescriptor找到序列化程序,也没有发现创建BeanSerializer的属性
(为避免exception,请禁用SerializationFeature.FAIL_ON_EMPTY_BEANS))
(通过参考链:
org.springframework.core.io.FileSystemResource [\ “的OutputStream \”] – > java.io.FileOutputStream中[\ “FD \”]);
嵌套exception是com.fasterxml.jackson.databind.JsonMappingException:没有找到类java.io.FileDescriptor的序列化器,也没有发现创建BeanSerializer的属性
(为避免exception,请禁用SerializationFeature.FAIL_ON_EMPTY_BEANS))
(通过参考链:org.springframework.core.io.FileSystemResource [\“outputStream \”] – > java.io.FileOutputStream [\“fd \”])

有谁知道如何解决它?

而且,我应该如何从客户端发送(JavaScript,jQuery)?

编辑2:首先 – 见底部的编辑1 – 这不是正确的方法。 但是,如果您无法使序列化程序工作,您可以使用此解决方案,将XML文件读入字符串,并促使用户保存它:

 @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(); } 

那应该做的。 但请记住,浏览器会缓存URL内容 – 因此,对每个文件使用唯一的URL可能是个好主意。

编辑:

在进一步检查之后,您还应该能够将以下代码添加到您的Action中,以使其工作:

 response.setContentType("text/plain"); 

(或者对于XML)

 response.setContentType("application/xml"); 

所以你的完整解决方案应该是:

 @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 }