代码语言:javascript复制
public void downloadFile(HttpServletRequest request, HttpServletResponse response, Integer type) throws FileNotFoundException, IOException {
String fileName = “中文文件名.docx";
XWPFDocument xdoc = null;
FileInputStream is = null;
OutputStream out = null;
try {
System.out.println("----------userAgent=" request.getHeader("User-Agent"));
String agent = request.getHeader("User-Agent");
boolean isMSIE = ((agent != null && agent.indexOf("MSIE") != -1 ) || ( null != agent && -1 != agent.indexOf("like Gecko")));
/**旧版本ie直接判断MSIE即可,但是新版本ie跟edge使用了新的内核。msie判断无效,打印agent,先做截取处理。 但是chrome打印出来也包含like Gecko,所以这里chrome等浏览器打印出来也会走gbk的编码,但是不会出现乱码。解决。**/
if(isMSIE){
System.out.println("----ie内核");
fileName = new String(fileName.getBytes("GBK"),"ISO8859-1");
} else {
System.out.println("------chrome");
fileName = new String(fileName.getBytes("UTF8"), "ISO8859-1");
}
// if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
// System.out.println("----ie内核");
// fileName = new String(fileName.getBytes("GBK"),"ISO8859-1");
// }else if(request.getHeader("User-Agent").toUpperCase().indexOf("Edge") > 0){
// System.out.println("----edge");
// fileName = new String(fileName.getBytes("GBK"),"ISO8859-1");
// }else{//firefox、chrome、safari、opera
// System.out.println("------chrome");
// fileName = new String(fileName.getBytes("UTF8"), "ISO8859-1");
// }
// fileName = new String(fileName.getBytes(), "iso-8859-1");
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=" fileName);
if (type != null && type.equals(1)) {
is = new FileInputStream(templateExcelDir "/daoluceshishenqingbiao.docx");
} else {
is = new FileInputStream(templateExcelDir "/daoluceshiguanlibanfa.docx");
}
out = response.getOutputStream();// 获得一个output对象
xdoc = new XWPFDocument(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
xdoc.write(out);
is.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}