spring 工程中模版文件下载
文件放置位置
将模版文件放到resources下
代码
import org.springframework.core.io.ClassPathResource;
import javax.servlet.ServletOutputStream;
import java.io.ByteArrayOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
public void downTemplete(HttpServletResponse response) {
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
//设置响应头信息,包括下载后的文件名和编码等
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("人员费用明细导入模板", "UTF-8") + ".xlsx");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
//在文件夹里获取到文件并转为流
inputStream = new ClassPathResource("templates/CostWorkers.xlsx").getInputStream();
byte[] buffer = new byte[1024];
int bytesRead;
byteArrayOutputStream = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
}
response.getOutputStream().write(byteArrayOutputStream.toByteArray());
} catch (Exception e) {
log.error("下载模板异常", e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
log.error("关闭inputStream异常", e);
}
try {
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
} catch (IOException e) {
log.error("关闭byteArrayOutputStream异常", e);
}
try {
if (response.getOutputStream() != null) {
response.getOutputStream().close();
}
} catch (IOException e) {
log.error("关闭OutputStream异常", e);
}
}
}
纸上得来终觉浅,绝知此事要躬行。