public void downloadExistsFile(HttpServletRequest request, HttpServletResponse response, File proposeFile) throws IOException, FileNotFoundException {
response.reset();
OutputStream outputStream=null;
InputStream inputStream=null;
log.debug("下载文件路径:" + proposeFile.getPath());
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + proposeFile.getName());
response.setHeader("Accept-Ranges", "bytes");
long currentLen = 0;// 已读取文件大小
long totleLen = proposeFile.length();// 总文件大小
long start=0;//读取的开始位置,默认0
long end=proposeFile.length()-1;//读取的结束位置,默认读完
if (null != request.getHeader("Range")) {
// 断点续传
// 若客户端传来Range,说明之前下载了一部分,设置206状态(SC_PARTIAL_CONTENT)
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
try {
String range = request.getHeader("Range");
int index = range.indexOf("=");
int ed = range.indexOf("-");
start=Long.parseLong(range.substring(index + 1, ed));
try {
end=Long.parseLong(range.substring(ed+1, range.length()));
}catch (Exception e) {
//如果没有指定结束位置,则读完整个文件
end=proposeFile.length()-1;
}
//如果读取的结束位置大于文件长度,则结束位置设置为文件长度-1
if (end>=proposeFile.length()){
end=proposeFile.length()-1;
}
} catch (NumberFormatException e) {
log.error(request.getHeader("Range") + " is not Number!");
}
}
//本次发送的文件长度
Long rangeLength=end - start + 1;
response.setHeader("Content-Length", String.valueOf(rangeLength));
//本次读取文件的信息,包括开始位置,结束位置,文件总大小
response.setHeader("Content-Range", String.format("bytes %s-%s/%s", start, end, proposeFile.length()));
try {
outputStream = response.getOutputStream();
inputStream = new FileInputStream(proposeFile);
inputStream.skip(start);
byte[] buffer = new byte[5 * 1024];
int length = 0;
while (currentLen<rangeLength) {
length=inputStream.read(buffer,0,(rangeLength-currentLen)<=buffer.length ?
(int)(rangeLength-currentLen) : buffer.length);
currentLen+=length;
outputStream.write(buffer,0,length);
}
outputStream.flush();
log.info("本次下载量/本次需要下载的总大小{}/{},文件总大小{}",currentLen,rangeLength,totleLen);
}catch (Exception e){
log.error("下载中断或者网络异常表示没下载完");
log.info("本次下载量/本次需要下载的总大小{}/{},文件总大小{}",currentLen,rangeLength,totleLen);
}finally {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}