搬砖过程中常用的springBoot下载代码模板,复制用就行了。【2022-11-29 为方便小白,二次更新】
一、controll
//controll 层
@GetMapping("/excelDown")
public void dataModuleExcelDown(HttpServletRequest request,
HttpServletResponse response) throws UnsupportedEncodingException {
dataCategoryService.excelDown(request,response);
}
二、server
//server层
public void excelDown(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
//1.读取文件流
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String prefix = ".xlsx";
String fileName = "template";
String filePath = "/template/" + fileName + prefix;
ClassPathResource classPathResource = new ClassPathResource( filePath );
InputStream in = classPathResource.getStream();
request.setCharacterEncoding( "UTF-8" );
String userAgent = request.getHeader( "User-Agent" );
try {
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE浏览器的处理:
fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
}
response.reset();
response.setContentType( "application/octet-stream" );
response.addHeader( "content-disposition", "attachment; filename=" + fileName + prefix);
bis = new BufferedInputStream( in );
bos = new BufferedOutputStream( response.getOutputStream() );
byte[] bytes = new byte[2048];
int len;
while ( (len = bis.read( bytes, 0, bytes.length )) != -1 ) {
bos.write( bytes, 0, len );
}
} catch (Exception e) {
throw new RuntimeException( e );
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
三、资源文件路径
四、坑,如果有下载下来打不开的,参考我这篇文章