情景:项目中有时会出现,在服务上下载文件
实现代码如下:
/**
* 操作手册下载
*/
@RequestMapping(value = "/downFile")
public void downFile(String downType, HttpServletResponse response) {
try {
if (StringUtils.isNotEmpty(downType)) {
ServletOutputStream ouputStream = null;
InputStream is = null;
byte[] bytes = null;
Connection conn = null;
String fileName="服务系统操作手册.docx";
String url = "";
try {
String basePath = Global.getUserfilesBaseDir();//服务器上存放文件路径
url ="服务系统操作手册.docx";//文件名称 我这为空展示下载docx格式文件下载
String destpath = basePath + url;
File destfile = new File(destpath);
String type = url.substring(url.lastIndexOf(".") + 1);
if (destfile.exists()) {
FileInputStream inputStream = new FileInputStream(destfile);
bytes = IOUtils.toByteArray(inputStream);
response.setContentType("application/msword;charset=UTF-8");
if ("pdf".equals(type)) {
response.setContentType("application/pdf;charset=UTF-8");
} else if ("doc".equals(type) || "docx".equals(type)) {
response.setContentType("application/msword;charset=UTF-8");
} else if ("xls".equals(type) || "xlsx".equals(type)) {
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
}
response.setContentLength(bytes.length);
ouputStream = response.getOutputStream();
ouputStream.write(bytes, 0, bytes.length);
ouputStream.flush();
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (ouputStream != null) {
ouputStream.close();
}
if (conn != null) {
conn.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
LoggerUtils.debug(logger, "print " + e);
}
}
ok ^ _ ^ 这次就到这里啦