1.引入SpringBoot和hutool依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.22</version>
</dependency>
2.在项目resources目录下放入模版文件,结构如下:
3.定义文件下载接口
@SneakyThrows(IOException.class)
@ApiOperation(value = "下载模版文件", notes = "下载模版文件")
@RequestMapping(value = "/down_template", method = RequestMethod.GET)
public Response<Void> downTemplate(@RequestParam(required = false)String templateName, HttpServletResponse response) {
if(StringUtils.isBlank(templateName)){
return null;
}
response.setCharacterEncoding("utf-8");
try (InputStream templateInputStream = this.getClass().getResourceAsStream("/template/" + templateName);
OutputStream outputStream = response.getOutputStream()) {
Asserts.notNull(templateInputStream, "templateInputStream is null");
//获取文件字节数组
byte[] bytes = IoUtil.readBytes(templateInputStream);
//获取文件mimetype,也就是contenttype
FileMagicNumber magicNumber = FileMagicNumber.getMagicNumber(bytes);
if(magicNumber != FileMagicNumber.UNKNOWN){
response.setContentType(magicNumber.getMimeType());
String fileName = URLEncoder.encode("模版文件" + DateUtil.format(new Date(), "yyyyMMdd"), "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment; filename=" + fileName + "." + magicNumber.getExtension());
}
outputStream.write(bytes, 0, bytes.length);
}
return null;
}
4.postman请求改接口,然后把文件流保存到本地目录,说明下载成功