public void downLoadFiles(FileDownloadReqVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
String absolutePath = reqVO.getAbsolutePath();
// 设置下载的文件名
String fileName = absolutePath.substring(absolutePath.lastIndexOf("/") + 1).toUpperCase();
// 读取要下载的文件,保存到文件输入流
FileInputStream in = new FileInputStream(absolutePath);
// 创建输出流
OutputStream out = response.getOutputStream();
try {
// 设置响应头,控制浏览器下载该文件
this.setResponseHeader(response, fileName);
// 缓存区
byte buffer[] = new byte[1024];
int len = 0;
// 循环将输入流中的内容读取到缓冲区中
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
// 关闭
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送响应流方法
* @param response
* @param fileName
*/
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes("gbk"), "iso8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 定义输出类型
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
} catch (Exception ex) {
ex.printStackTrace();
}
}
参考以下链接