需要提供一个界面能够下载系统日志文件,就在后台管理系统中做了一个系统日志下载界面。
项目用的是play框架,之前没有做过play框架下载文件,所以尝试着做了一下,示例代码如下:
/**
* 日志文件夹主目录名
*/
public static final String LOGDIRECTORYHOME = "XXXX";
/**
* 文件下载
* @param fileName 文件所在的目录名称
* @param subFileName 文件名
* @return
*/
public static Result download(String fileName, String subFileName) {
String filePath = System.getProperty("user.dir") + File.separator + LOGDIRECTORYHOME + File.separator + fileName + File.separator + subFileName;
play.mvc.Http.Response response = response();
File file = new File(filePath);
// 取得文件名。
String filename = file.getName();
try {
response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"),"ISO8859_1"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
response.setHeader("Content-Length", "" + file.length());
response.setContentType("application/octet-stream");
byte[] buffer = {};
try {
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
} catch (IOException e) {
if (Logger.isErrorEnabled()) {
Logger.error("下载文件" + filePath + "出错。", e);
}
}
return ok(buffer);
}