问题描述
我已经尝试了很多从控制器函数返回文件。
I have tried a lot to return a file from the controller function.
这是我的功能:
@RequestMapping(value = "/files", method = RequestMethod.GET)
@ResponseBody public FileSystemResource getFile() {
return new FileSystemResource(new File("try.txt"));
}
我收到此错误消息:
有没有人知道如何解决它?
Does anyone have an idea how to solve it?
而且,我应该如何从客户端发送(JavaScript,jQuery)?
And, how should I send from the client (JavaScript, jQuery)?
推荐答案
编辑2:首先 - 参见底部的编辑1 - 这是正确的方法。但是,如果您无法使序列化程序工作,您可以使用此解决方案,将XML文件读入字符串,并促使用户保存它:
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.
编辑:
经过进一步检查后,您还应该能够将以下代码添加到您的操作中,以使其正常工作:
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");
(或者对于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
}
这篇关于从spring MVC控制器返回xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!