文件下载是一个经常用到的功能,这里做一简单记录,以备不时之需。
public static void downloadFileInfo(HttpServletRequest request, HttpServletResponse response) {
boolean success = true;
// 提示信息
String msg = "";
// 下载文件Id
String mFileId = request.getParameter("fileId");
if (mFileId == null) {
success = false;
msg = "文件下载地址参数有误!";
log.error("文件下载地址没有参数fileId");
} else {
// 加载文件记录
FileInfo fileInfo = fileInfoService.loadFileInfo(mFileId);
// 判断文件记录是否存在
if (fileInfo == null) {
success = false;
msg = "文件记录不存在!";
log.error("文件记录[fileId=" + mFileId + "]不存在");
} else {
// 判断文件是否存在
String filePath = fileInfo.getFilePath();
String downloadName = fileInfo.getFileName() + "." + fileInfo.getFileExt();
String fullFilePath = filePath + File.separatorChar + downloadName;
File downloadFile = new File(fullFilePath);
if (!downloadFile.exists()) {
success = false;
msg = "文件在服务器上不存在";
log.error("文件[filePath=" + fullFilePath + "]不存在");
} else {
// 下载文件
FileInputStream inStream = null;
OutputStream outStream = null;
try {
// 指定文档contentType
String contentType = fileInfo.getContentType();
if (contentType != null && contentType.trim().length() > 0) {
response.setContentType(contentType);
} else {
response.setContentType("application/x-msdownload");
}
// 下载文件显示名
String downloadTitle = fileInfo.getFileTitle().trim()
+ "." + fileInfo.getFileExt();
downloadTitle = URLEncoder.encode(downloadTitle, "GB2312");
downloadTitle = URLDecoder.decode(downloadTitle, "ISO8859_1");
// 指定响应头
response.setHeader("Content-disposition", "attachment;filename=" + downloadTitle);
inStream = new FileInputStream(fullFilePath);
outStream = response.getOutputStream();
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = inStream.read(buffer, 0, 8192)) > 0) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
} catch (Exception e) {
success = false;
msg = "下载文件出错,请与系统管理员联系!";
e.printStackTrace();
} finally {
try {
if (inStream!= null) {
inStream.close();
}
if (outStream != null) {
outStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
// 输出错误提示信息
if (success == false) {
try {
String encodeMsg = new String(msg.getBytes(), "ISO-8859-1");
response.getWriter().write("<script type=\"text/javascript\">");
response.getWriter().write("alert(\"" + encodeMsg + "\");");
response.getWriter().write("history.back();");
response.getWriter().write("</script>");
response.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}