response.setHeader("Content-Disposition", String.format("inline; filename=\"%s\"", StringUtil.toEncodedString(fileDescriptionDTO.getName().getBytes(), Charset.forName("ISO-8859-1"))));
List<String> videoTypes= Arrays.asList("mp4","webm","ogg","avi","mov","wmv","rmvb","mkv","m4v","mp3","wma","rm");
Long startByte = null;
Long endByte = null;
Long contentLength = null;
if (videoTypes.contains(fileDescriptionDTO.getSuffix())){
//开始下载位置
startByte = 0L;
//结束下载位置
Long fileLength = fileDescriptionDTO.getSize();
endByte = fileLength - 1;
log.debug("文件开始位置:{},文件结束位置:{},文件总长度:{}", startByte, endByte, fileLength);
//有range的话
String range = request.getHeader("Range");
if (range != null && range.contains("bytes=") && range.contains("-")) {
range = range.substring(range.lastIndexOf("=") + 1).trim();
String[] ranges = range.split("-");
try {
//判断range的类型
if (ranges.length == 1) {
//类型一:bytes=-2343
if (range.startsWith("-")) {
endByte = Long.parseLong(ranges[0]);
}
//类型二:bytes=2343-
else if (range.endsWith("-")) {
startByte = Long.parseLong(ranges[0]);
}
}
//类型三:bytes=22-2343
else if (ranges.length == 2) {
startByte = Long.parseLong(ranges[0]);
endByte = Long.parseLong(ranges[1]);
}
} catch (NumberFormatException e) {
startByte = 0L;
endByte = fileLength - 1;
log.error("Range Occur Error,Message:{}",e.getLocalizedMessage());
}
}
//要下载的长度
contentLength = endByte - startByte + 1;
//文件名
String fileName = fileDescriptionDTO.getName();
//文件类型
String contentType = request.getServletContext().getMimeType(fileName);
// 解决下载文件时文件名乱码问题
byte[] fileNameBytes = fileName.getBytes(StandardCharsets.UTF_8);
fileName = new String(fileNameBytes, 0, fileNameBytes.length, StandardCharsets.ISO_8859_1);
//各种响应头设置
//支持断点续传,获取部分字节内容:
response.setHeader("Accept-Ranges", "bytes");
//http状态码要为206:表示获取部分内容
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setContentType(contentType);
response.setHeader("Content-Type", contentType);
//inline表示浏览器直接使用,attachment表示下载,fileName表示下载的文件名
response.setHeader("Content-Disposition", "inline;filename=" + fileName);
response.setHeader("Content-Length", String.valueOf(contentLength));
// Content-Range,格式为:[要下载的开始位置]-[结束位置]/[文件总大小]
response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + fileLength);
}