以下是通过springmvc下载项目中的excel模板文件示例代码:
@ApiOperation("下载excel模板")
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(HttpServletRequest request,
HttpServletResponse response) throws Exception {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
request.setCharacterEncoding("UTF-8");
String prefix=".xlsx";
String fileName="excelTemplate";
String filePath = "/template/" + fileName+prefix;
ClassPathResource classPathResource = new ClassPathResource(filePath);
InputStream inputStream =classPathResource.getInputStream();
String userAgent = request.getHeader("User-Agent");
String downLoadPath = URLDecoder.decode(filePath, "UTF-8");
System.out.println(downLoadPath);
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.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + fileName+prefix);
response.setHeader("filename",fileName);
bis = new BufferedInputStream(inputStream);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}