使用206状态码实现断点续传(俗称拖进度条)
设置maxSize实现分片上传
直接上代码!
@GetMapping("/t1.jspx")
public void video(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 表示这是视频文件
response.setContentType("video/mp4");
String range = request.getHeader("Range");
// 第一次请求时range为null
if(range == null){
response.setHeader("Accept-Ranges", "bytes");
response.addHeader("Content-Disposition", "inline;filename=" + fileName);
return;
}
// 如果有range,就请求数据(path和filenName为预先定义好的)
File file = new File(path + "\\" + fileName);
FileInputStream fileInputStream = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
int contentLength = fileInputStream.available();
// 获取起止,end默认为0
int start = 0, end = 0;
if(range.startsWith("bytes=")){
String[] values = range.split("=")[1].split("-");
start = Integer.parseInt(values[0]);
if(values.length > 1){
end = Integer.parseInt(values[1]);
}
}
//断点续传 206
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
// 每次传递实际长度
long length = 0;
// 允许的最大长度
long maxSize = 1024L * 1024L;
if(end > 0){
// 一般不会这样
length = end - start + 1;
response.setHeader("Content-length", "" + length);
response.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + contentLength);
}else{
// 大部分情况end为0
length = ((contentLength - start) > maxSize) ? maxSize : (contentLength - start);
response.setHeader("Content-length", "" + length);
response.setHeader("Content-Range", "bytes "+ start + "-" + (start + length - 1) + "/" + contentLength);
}
// 将数据截取并存入byte[]数组中
byte[] data = new byte[(int)length];
fileInputStream.skip(start);
fileInputStream.read(data);
// 取出要传给前端的有效数据
out.write(data);
out.close();
fileInputStream.close();
}