如何在Spring中使用FileSystemResource正确下载文件?

时间:2015-12-05 12:15:51

标签: spring spring-mvc download spring-boot

我有以下代码用于下载文件: -

@Controller
public class FileController {
    @RequestMapping(value = "/files/{file_name:.+}", method = RequestMethod.GET)
    @ResponseBody
    public FileSystemResource getFile(@PathVariable("file_name") String fileName) {

        return new FileSystemResource("C:/Users/sourav/fileServer/"+fileName);

    }

}

当我第一次进入链接时,没有显示任何内容。当我重新加载时,只下载名为f.txt的文本文件而不是pdf文件。我希望pdf文件显示在浏览器中。如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

你的代码还可以。我想如果您尝试使用pdf文件,它将按预期工作,它将显示在浏览器中。我测试了它并在Chrome和Firefox中运行良好。可能是您的测试文件已损坏。

答案 1 :(得分:0)

如果您使用的是Spring Boot,则可以将要下载的文件的MIME类型添加到配置文件中的spring.mvc.mediaTypes属性中。例如:

spring.mvc.mediaTypes.yml=text/yaml

来源:https://github.com/spring-projects/spring-boot/issues/4220

答案 2 :(得分:0)

我认为您需要设置响应标头。否则浏览器无法直观地使用文件格式。类似于response.setContentType("application/pdf");

相关问题