Java-读取resource目录下的文件并返回给前端
我在项目的resource目录下面放了一个模板文件,用来供用户下载
提供一个接口给前端,用来下载
在Utils类下面写个方法来读取
代码
public static void getXMindTemplate(HttpServletResponse response){
String fileName = "templates/TestCaseTemplate.xmind"; // 文件名称
ClassPathResource classPathResource = new ClassPathResource(fileName);
try {
InputStream inputStream = classPathResource.getInputStream();
response.setContentType("application/octet-stream;charset=utf-8");
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(FileUtil.getName(fileName), "UTF-8"));
int len = 0;
byte[] buffer = new byte[1024];
OutputStream outputStream = response.getOutputStream();
while((len=inputStream.read(buffer))>0) {
outputStream.write(buffer, 0, len);
}
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception e){
log.error("下载XMind格式的测试用例模版失败:{}",e.getMessage());
}
}