微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 从spring MVC控制器返回xml文件

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

这是我的功能

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。