/**
*
* @downloadFile(下载app文件,监控是否下载完成)1
* @作者:dww
* @创建时间:2018年1月30日 下午1:56:35
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/downloadFile")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
InputStream ins = null;
BufferedInputStream bins = null;
OutputStream outs = null;
BufferedOutputStream bouts = null;
String fileName = "10008328_com.tencent.tmgp.xymobile_h100_1.0.30.1.apk";
String path = PropertiesUtils.getConfigProperty("appFileSavePath") + "/" + fileName;
File file = new File(path);
if (!file.exists()) {
logger.info("文件不存在");
return;
}
long currentLen = 0;// 已读取文件大小
long totleLen = file.length();// 总文件大小
double percent=0.0; //下载进度
try {
ins = new FileInputStream(path);
bins = new BufferedInputStream(ins);// 放到缓冲流里面
outs = response.getOutputStream();// 获取文件输出IO流
bouts = new BufferedOutputStream(outs);
response.setContentType("application/x-download");// 设置response内容的类型
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));// 设置头部信息
int bytesRead = 0;
byte[] buffer = new byte[1024];
// 开始向网络传输文件流
while ((bytesRead = bins.read(buffer)) != -1) {
currentLen += bytesRead;
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();// 这里一定要调用flush()方法
// 获取下载进度
percent = Math.ceil(currentLen * 1.0 / totleLen * 10000);
logger.info("下载 进度:",percent/100.0+"%");
if(percent == 10000) {
logger.info("下载完成了");
}
} catch (IOException e) {
percent = Math.ceil(currentLen * 1.0 / totleLen * 10000);
logger.error("下载中断或者网络异常表示没下载完,当前下载进度:{};{}",percent/100.0 +"%",e.getMessage(),e);
} finally {
if (ins != null) {
ins.close();
}
if (bins != null) {
bins.close();
}
if (outs != null) {
outs.close();
}
if (bouts != null) {
bouts.close();
}
}
}