需求:用户点击下载按钮,将本地文件响应给用户
方法一:
//controller 层
@RequestMapping("/testDownloadFile.do")
public void testDownloadFile(HttpServletResponse response){
InputStream inputStream=null;
try {
File file = new File("E:\\others\\fileTest.txt");
inputStream=new FileInputStream(file);
GetClient.fileDownload(file.getName(),inputStream,response);
}catch (Exception e){
e.printStackTrace();
log.error("出现异常了,请稍后重试");
}
}
//文件下载方法,可以防止util中
public static void fileDownload(String filename, InputStream input, HttpServletResponse response){
try {
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
//关闭,即下载
toClient.close();
}catch (Exception e){
e.printStackTrace();
}
}
测试:
测试:正常下载,通过!
方法二:
//controller 层
@RequestMapping("/testDownloadFile.do")
public void testDownloadFile(HttpServletResponse response){
InputStream inputStream=null;
try {
File file = new File("E:\\others\\fileTest.txt");
inputStream=new FileInputStream(file);
GetClient.fileDownload(file.getName(),inputStream,response);
}catch (Exception e){
e.printStackTrace();
log.error("出现异常了,请稍后重试");
}
}
//文件下载方法,可以防止util中
public static void fileDownload(String filename, InputStream input, HttpServletResponse response){
try {
byte[] buffer = new byte[4096];
int readLength = 0;
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
while ((readLength=input.read(buffer)) > 0) {
byte[] bytes = new byte[readLength];
System.arraycopy(buffer, 0, bytes, 0, readLength);
toClient.write(bytes);
}
input.close();
toClient.flush();
toClient.close();
}catch (Exception e){
e.printStackTrace();
}
}
测试:正常下载,通过!
总结
方法二在方法一的基础上进行了优化,在实现功能的基础上考虑了性能。从上面代码可以看出,方法一在大文件下载时会占用很多内存资源,多个用户同时下载大文件会存在宕机的隐患 。实际项目中该功能是从分布式文件存储系统上下载文件响应给用户,本例进行了简化。