优化前
public void download(String fileUUID, HttpServletResponse response) throws IOException {
// 根据文件的唯一标识码获取文件
File uploadFile = new File(fileUploadPath + fileUUID);
// 设置输出流的格式
ServletOutputStream os = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
response.setContentType("application/octet-stream");
// 读取文件的字节流
os.write(FileUtil.readBytes(uploadFile));
os.flush();
os.close();
}
为了实现优化要求,可以先判断 fileUUID 是否为空或者文件是否存在,如果不满足条件则直接返回,否则再执行后续的代码。下面是实现这个功能的改进版本:
@Override
public void download(String fileUUID, HttpServletResponse response) throws IOException {
// 判断 fileUUID 是否为空
if (StrUtil.isBlank(fileUUID)) {
return;
}
// 根据文件的唯一标识码获取文件
File uploadFile = new File(fileUploadPath + fileUUID);
// 判断文件是否存在
if (!uploadFile.exists()) {
return;
}
// 设置输出流的格式
ServletOutputStream os = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
response.setContentType("application/octet-stream");
// 读取文件的字节流
os.write(FileUtil.readBytes(uploadFile));
os.flush();
os.close();
}
在新版本中增加了两个判断,分别用来判断 fileUUID 是否为空和文件是否存在,如果满足其中一个条件则直接返回,不执行后续代码,也就不会抛出异常了。这样,调用该方法时如果传入的 fileUUID 为空或者对应的文件不存在,就会静默地忽略这个请求,不会抛出错误,避免了不必要的异常抛出。