根据视频一边加载一边播放
package cn.com.cgnpc.luin.common.utils;
import org.springframework.http.HttpStatus;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class VideoUtil {
public static void displayMp4(HttpServletRequest request, HttpServletResponse response, File file) throws IOException {
if (!file.exists() || !file.getName().endsWith(".mp4")) {
response.getOutputStream().close();
return;
}
String range = request.getHeader("Range");
if ( range != null && Pattern.matches("[0-9A-Za-z=-]+", range) && range.length() > 7) {
range = range.substring(6);
String[] arr = range.split("-");
long lenStart = Long.parseLong(arr[0]);
long end = 0;
if (arr.length > 1) {
end = Long.parseLong(arr[1]);
}
// long contentLength = end > 0 ? (end - (lenStart - 1)) : (file.length() - (lenStart > 0 ? lenStart - 1 : 0));//如果指定范围,就返回范围数据长度,如果没有就返回剩余全部长度
// response.setHeader("Content-Length", String.valueOf(contentLength));
// response.setHeader("Content-Disposition", "attachment; filename=\"" + System.currentTimeMillis() + ".mp4" + "\"");//不能用中文
response.setHeader("Content-Range", "bytes " + lenStart + "-" + (end > 0 ? end : (file.length() - 1)) + "/" + file.length());
response.setContentType("video/mp4; charset=UTF-8");
response.setStatus(HttpStatus.PARTIAL_CONTENT.value());//响应码206表示响应内容为部分数据,需要多次请求
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
randomAccessFile.seek(lenStart);//设置读取的开始字节数
if (end > 0) {//客户端指定了范围的数据,那就只给范围数据
int size = (int) (end - lenStart + 1);
byte[] buffer = new byte[size];
int len = randomAccessFile.read(buffer);
if (len != -1) {
response.getOutputStream().write(buffer, 0, len);
}
} else {//没有指定范围
//视频每次返回一兆数据
int size = 1048576;//1MB
byte[] buffer = new byte[size];
int len;
while ((len = randomAccessFile.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, len);
}
}
randomAccessFile.close();
} else {
response.setHeader("Content-Disposition", "attachment; filename=\"" + System.currentTimeMillis() + ".mp4" + "\"");//不能用中文
// response.setHeader("Content-Length", String.valueOf(file.length() - 1));
// response.setHeader("Content-Range", "" + (file.length() - 1));
response.setContentType("video/mp4; charset=UTF-8");
InputStream inStream = Files.newInputStream(file.toPath());
byte[] buffer = new byte[1024];
int len;
while ((len = inStream.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, len);
}
inStream.close();
}
response.getOutputStream().flush();
response.getOutputStream().close();
}
}