从spring MVC控制器返回xml文件

Rat*_*Rat 6 java xml spring file spring-mvc

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

这是我的功能:

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

我收到此错误消息:

无法编写JSON:
找不到类java.io.FileDescriptor的序列化程序,也没有发现创建BeanSerializer的属性
(为了避免异常,禁用SerializationFeature.FAIL_ON_EMPTY_BEANS))
(通过引用链:
org.springframework.core.io.FileSystemResource [\"的OutputStream\"] - > java.io.FileOutputStream中[\" FD \"]);
嵌套异常是com.fasterxml.jackson.databind.JsonMappingException:没有为类java.io.FileDescriptor找到序列化器,也没有发现创建BeanSerializer的属性
(为了避免异常,禁用SerializationFeature.FAIL_ON_EMPTY_BEANS))
(通过引用链:org.springframework. core.io.FileSystemResource [\ "的OutputStream \"] - > java.io.FileOutputStream中[\ "FD \"])

有谁知道如何解决它?

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

Mic*_*rly 5

编辑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();
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

response.setContentType("text/plain");
Run Code Online (Sandbox Code Playgroud)

(或者对于XML)

response.setContentType("application/xml");
Run Code Online (Sandbox Code Playgroud)

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

@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 
}
Run Code Online (Sandbox Code Playgroud)