import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 对下载进行记录切面类
*/
@Aspect
@Component
@Slf4j
public class DownLogAspect {
@Autowired
private DownLogHelper downLogHelper;
//拦截工具包FileHelper类以download开头的方法
@Pointcut("execution(public * cn.com.utils.FileHelper.download*(..))")
public void downLoadFileCut() {
}
//记录下载信息
@AfterReturning(pointcut = "downLoadFileCut()", returning = "result")
public Object savedownLoadLog(JoinPoint jp, Boolean result) {
Object[] args = jp.getArgs();
DownloadLog downloadLog = null;
//根据返回值判断文件是否下载成功
if (result) {//成功
downLogHelper.downloadLog(FileLoadStatus.Download_Suucess.getValue(),String.valueOf(args[2]),String.valueOf(args[3]));
log.info("对下载进行记录,记录文件"+ FileLoadStatus.Download_Suucess.getValue());
} else {//失败
downLogHelper.downloadLog(FileLoadStatus.Download_Failed.getValue(),String.valueOf(args[2]),String.valueOf(args[3]));
log.info("对下载进行记录,记录文件"+ FileLoadStatus.Download_Failed.getValue());
}
return result;
}
}
package cn.com.utils;
@Component
@Slf4j
public class FileHelper {
public boolean download(HttpServletRequest request, HttpServletResponse response, String relativePath, String downloadName)
throws Exception {
boolean isSuccess=true;
setFilePath();
String path="";
if(!StringUtil.isEmpty(rootPath)){
path = rootPath + File.separator + relativePath;
}else {
path=relativePath;
}
Date startDate = new Date();
log.info("文件" + path + "下载开始===========" + startDate);
File file = new File(path);
if (file.exists()) {
InputStream in = null;
ServletOutputStream outputStream = null;
try {
in = new FileInputStream(file);
//处理IE下载文件的中文名称乱码的问题
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
downloadName = URLEncoder.encode(downloadName, "utf-8");
downloadName = downloadName.replace("+", "%20"); //IE下载文件名空格变+号问题
} else {
downloadName = new String(downloadName.getBytes(), "iso-8859-1");
}
byte[] bytes = new byte[1024];
int len = 0;
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.addHeader("Content-Disposition",
"attachment;filename=" + downloadName);
outputStream = response.getOutputStream();
if (file.length() == 0) {
outputStream.write(in.available());
} else {
while ((len = in.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
}
log.info("文件下载输出成功!!!!!=====用时:" + TimeUtil.calLastedTime(startDate) + "毫秒");
} catch (Exception e) {
isSuccess=false;
log.error("文件下载失败");
} finally {
if (in != null || outputStream != null) {
try {
in.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
isSuccess=false;
log.info("文件" + path + "不存在");
}
return isSuccess;
}
}