您好,我正在尝试创建一个允许我托管任何类型文件的应用程序。 为了做到这一点,我正在执行以下魔法:
@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody
public FileSystemResource
getFile(
@PathVariable("file_name") String fileName) {
System.out.println(fileName);
String filePath = "./files/";
return new FileSystemResource(new File(filePath+fileName));
}
但是这种方法带来了三个不必要的问题:
一些随机数据被附加到文件中
文件在浏览器窗口中打开而不是蜂鸣 下载 - 我试过用类似
的东西来破解它produces = "application/octet-stream"
但这只会导致 406 错误。
test.txt 被截断为测试,我找到了一种解决方法,即为应用程序提供 test.txt/作为文件名,但它看起来有点乱。
最佳答案
如 spring manual 所述
As with @RequestBody, Spring converts the returned object to a response body by using an HttpMessageConverter
我认为你的问题是 spring 没有提供可以处理 FileSystemResource 的 HttpMessageConverter。
A list of builtin HttpMessageConverter is available here .我建议您尝试以某种方式将您的响应转换为字节数组,也许它会选择 ByteArrayHttpMessageConverter 来帮助解决您的问题
关于java - 使用 ResponseBody 下载 spring 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14470270/