在我们开发中很多时候需要让我们的客户从服务器上下载模板等信息,在本人开发时也有遇到,特地在此记录一下,以便下次在用。
思路:在后台接口中,我们以流的方式将数据发送到前端,前端直接利用 <a href=“后台接口”> 标签请求后台接口。
代码如下:
controller层:
/**
* 下载人才信息服务模板
*
* @param response
* @return
*/
@RequestMapping(value = "/download",method = RequestMethod.GET)
@CatchErr
public ResultMsg<String> downloadTemplate(HttpServletResponse response){
ResultMsg<String> resultMsg = new ResultMsg<>();
try {
personnelInfoManager.downloadTemplate(response);
resultMsg = ResultMsg.SUCCESS("下载人才信息服务模板成功!");
} catch (IOException e) {
e.printStackTrace();
resultMsg = ResultMsg.ERROR("下载人才信息服务模板时异常!");
}
return resultMsg;
}
Service层:
/**
* 下载模板
* @param response
* @return
* @throws IOException
*/
ResultMsg<String> downloadTemplate(HttpServletResponse response) throws IOException;
ServiceImpl层(重要):以流的方式将文件从服务器上下载下来。
/**
* 下载模板
* @param response
* @return
* @throws IOException
*/
@Override
public ResultMsg<String> downloadTemplate(HttpServletResponse response) throws IOException{
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resourcePatternResolver.getResources("classpath:/template/personnelInfo.xlsx");
Resource resource = resources[0];
URI uri = resource.getURI();
logger.info(uri.toString());
InputStream inputStream = null;
OutputStream out = null;
try {
//根据文件在服务器的路径读取该文件转化为流
inputStream = resource.getInputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
String fileName = "人才信息导入模板.xlsx";
//设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
//设置文件头:最后一个参数是设置下载文件名(设置编码格式防止下载的文件名乱码)
response.setHeader("Content-Disposition", "attachment;fileName="+new String( fileName.getBytes("UTF-8"), "ISO8859-1" ));
out = response.getOutputStream();
int b = 0;
while (b != -1){
b = inputStream.read(buffer);
//写到输出流(out)中
out.write(buffer,0,b);
}
return null;
}catch (Exception e){
e.printStackTrace();
return ResultMsg.ERROR("下载人才信息导入模板异常!");
}finally {
try {
inputStream.close();
out.close();
out.flush();
}catch (Exception e){
e.printStackTrace();
}
}
}
html页面关键代码:
<form name="form">
<table class="form-table">
<tr>
<th>
下载导入模板
</th>
<td>
<a class='btn btn-primary fa fa-arrow-down ng-scope' href="/personnelInfo/download">下载模板</a>
</td>
</tr>
</table>
</form>
最后,因为我把下载路径指向了classpath:xxxx,即下面这段代码:
resourcePatternResolver.getResources("classpath:/template/personnelInfo.xlsx");
所以我们需要将我们的模板放到我们项目的根路径下。如下图: