这是我的功能:
@RequestMapping(value = "/files", method = RequestMethod.GET)
@ResponseBody public FileSystemResource getFile() {
return new FileSystemResource(new File("try.txt"));
}
我收到此错误消息:
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\”])
有谁知道如何解决它?
而且,我应该如何从客户端发送(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
}