SpringBoot下载resource目录下的资源文件

通过ClassPathResource加载文件所在的具体路径,然后通过getFile()获取到文件的输入流将输入流copy到输出流中,实现文件流的下载操作。

具体代码如下:

@RestController
@RequestMapping
public class Controller {
    @GetMapping("/test")
    public void download(HttpServletResponse response) {
        FileInputStream fis = null;
        ServletOutputStream sos = null;
        try {
            String fileName = "test.docx";
            // resources下路径,比如文件位置在:resources/file/test.docx
            String path = "file/" + fileName;
            //设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            ClassPathResource classPathResource = new ClassPathResource(path);
            fis = new FileInputStream(classPathResource.getFile());
            sos = response.getOutputStream();
            IOUtils.copy(fis, sos);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("下载失败!");
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (sos != null) {
                    sos.flush();
                    sos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
上一篇:halcon-gauss_filter高斯滤波


下一篇:【Zabbix】Zabbix基于SNMP监控配置