原下载方法:
/**
* 下载附件至指定目录
* @param mainId 关联Id
* @param fileName 文件名称
* @param tempath 目标下载目录
* @throws IOException
*/
public static File donwLoadFile(String mainId, String fileName, String tempath) throws IOException
{
// 获取附件管理服务
IBWAttachFileService service = FileManageUtil.getAchFileService();
// 根据主ID获取该主ID所关联的附件列表集合
List<AttachFileInfo> fileList = service.getAttachFileList(mainId);
File file = null;
if (null != fileList && fileList.size() > 0)
{
// 下载文件,返回字节流
byte[] bytes = service.downloadAttachFileData(fileList.get(0).getAttId());
// 根据字节流获取文件
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try
{
File dir = new File(tempath);
if (!dir.exists())
{
if (dir.mkdirs())
{
LOGGER.info("目标下载目录创建成功!");
}
}
file = new File(tempath + File.separatorChar + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
// 写出文件流
if (bytes != null)
{
bos.write(bytes);
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
// 关闭文件流
finally
{
if (null != bos)
{
try
{
bos.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
if (null != fos)
{
try
{
fos.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
return file;
}
修改后的:
修改后的:
/**
* 下载附件至指定目录
* @param mainId 关联Id
* @param fileName 文件名称
* @param tempath 目标下载目录
* @throws IOException
*/
public static File donwLoadFile(String mainId, String fileName, String tempath) throws IOException
{
// 获取附件管理服务
IBWAttachFileService service = FileManageUtil.getAchFileService();
// 根据主ID获取该主ID所关联的附件列表集合
List<AttachFileInfo> fileList = service.getAttachFileList(mainId);
if (null != fileList && fileList.size() > 0)
{
AttachFileInfo file = service.downloadAttachFile(fileList.get(0).getAttId());
downLoad(file.getData(), file.getFileName());
}
return null;
}
private static void downLoad(InputStream data, String fileName) throws IOException
{
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
response.setHeader("Content-disposition",
"attachment; filename=" + processDownFileName(fileName, request.getHeader("User-Agent")));
response.setContentType("application/x-download");
ServletOutputStream sos = response.getOutputStream();
byte[] b = new byte[10240];
int i = 0;
while ((i = data.read(b)) > 0)
{
sos.write(b, 0, i);
sos.flush();
}
sos.flush();
sos.close();
FacesContext.getCurrentInstance().responseComplete();
}
修改原因:通过使用缓冲流减少内存装载。
不使用缓冲流会每读一次就往硬盘里写一次。使用缓冲流会在内存里开辟一块区域暂时存放数据,每读一次就先把读到的数据写到缓冲区里,等区域里的数据装满或者执行了flush()方法,再把数据一次性的写入硬盘里,有利于提高效率