public void downloadFile(File file,HttpServletResponse response,boolean isDelete) {
try {
// 以流的形式下载文件。
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int i = -1;
while ((i = fis.read(buffer)) != -1) { //不能一次性读完,大文件会内存溢出(不能直接fis.read(buffer);)
toClient.write(buffer, 0, i);
}
fis.read(buffer);
fis.close();
// 清空response
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));
toClient.write(buffer);
toClient.flush();
toClient.close();
if(isDelete)
{
file.delete(); //是否将生成的服务器端文件删除
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}