通过springboot后端下载文件

需求是通过springboot后端将hdfs上的日志文件下载下来。hdfs中的文件内容通过cat获取,较为简单。主要记录一下如何将文件下载下来。

1
2
3
4
5
6
7
8
9
10
11
12
13
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downloadLog(HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setHeader("Content-Disposition", "attachment;fileName=a.txt");
String content = [日志内容];
try {
OutputStream os = response.getOutputStream();
os.write(content.getBytes(StandardCharsets.UTF_8));
os.close();
} catch (IOException ignored) {
}
}