1.springboot下的资源文件位置,如图:
2.java代码写在上图的src/main/java包下的一个controller里,具体代码如下:
package com.quanran.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Description: [外包人员信息controller]
* Created on 2018年02月01日
* @author <a href="mailto: 15175223269@163.com">全冉</a>
* @version 1.0
* Copyright (c) 2018年 全冉科技有限公司
*/
@Api(value = "外包人员信息管理相关接口", description = "外包人员信息管理相关接口")
@RestController
@RequestMapping("/outsourceUser")
public class EcmOutsourceUserController {
@Resource
private ResourceLoader resourceLoader;
/**
* <p>Discription:[下载模板功能]</p>
* Created on 2018年2月1日 上午11:57:59
* @param response response对象
* @param request response对象
* @author:[全冉]
*/
@ApiOperation("下载模板功能[15175223269@163.com]")
@GetMapping("/downloadTemplate")
public void downloadTemplate(HttpServletResponse response, HttpServletRequest request) {
InputStream inputStream = null;
ServletOutputStream servletOutputStream = null;
try {
String filename = "外包人员信息导入模板.xlsx";
String path = "template/outsourceUserInfo.xlsx";
org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:"+path);
response.setContentType("application/vnd.ms-excel");
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("charset", "utf-8");
response.addHeader("Pragma", "no-cache");
String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);
inputStream = resource.getInputStream();
servletOutputStream = response.getOutputStream();
IOUtils.copy(inputStream, servletOutputStream);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (servletOutputStream != null) {
servletOutputStream.close();
servletOutputStream = null;
}
if (inputStream != null) {
inputStream.close();
inputStream = null;
}
// 召唤jvm的垃圾回收器
System.gc();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}