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();
}
}
}
}
标签:fis,resource,SpringBoot,response,sos,test,new,null,目录 来源: https://blog.csdn.net/zhuocailing3390/article/details/123036748