1、首先使用Idea创建一个Spring Boot项目。
2、在application.properties文件下加入以下代码,进行DEBUG日志输出,配置pom.xml文件:
#logging日志配置
logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3、在resources/static文件夹下加入jquery-3.3.1.min.js和flvplayer.swf文件,当项目启动后,可以直接访问static文件下文件,例如http://localhost:8080/jquery-3.3.1.min.js可直接访问jquery文件。flvplayer.swf是播放flv格式视频的插件,在这先不详细介绍。
4、创建一个视频目录html页面:
因为项目采用前后端分离方案,不经过spring mvc转换访问页面,有兴趣的了解spring mvc的请看https://www.yiibai.com/spring_mvc/。
在<body>标签内加onload表示当页面加载时会自动调用js方法。
getPath()方法请求向后台获取所有的视频目录,ajax是异步请求,可将获取的数据添加到已有的html页面中,$("#view")为div的id,
- append() - 在被选元素的结尾插入内容
- prepend() - 在被选元素的开头插入内容
- after() - 在被选元素之后插入内容
- before() - 在被选元素之前插入内容
<!DCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>video menu</title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<script>
function getPath() {
$.ajax({
url:"http://localhost:8080/VideoPath",
type:"get",
success:function(path) {
$("#view").append("<table>");
var JsonPath = JSON.parse(path);
for(i=0;i<JsonPath.length;i++){
$("#view").append("<tr><td><a target='_blank' href='videoPlay.html?param="+JsonPath[i]+"'>"+JsonPath[i]+"</a></td></tr>");
}
$("#view").append("</table>");
}
})
}
</script>
<body onload="getPath()">
<div id="view"></div>
</body>
</html>
5、创建视频播放页面:
参数设置
-
vcastr_file
-
vcastr_title
-
vcastr_xml
-
IsAutoPlay
-
IsContinue
-
IsRandom
-
DefaultVolume
-
BarPosition
控制栏位置参数 :0表示在影片上浮动显示,1表示在影片下方显示 0 IsShowBar
BarColor
BarTransparent
播放控制栏透明度 60GlowColor
IconColor
TextColor
LogoText
LogoUrl
EndSwf
BeginSwf
IsShowTime
BufferTime
<!DOCTYPE html>
<html>
<head>
<title>video view</title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body onload="load()">
<script type="text/javascript">
function getParams(key) {
var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
};
function load(){
var txt = "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0\" width=\"500\" height=\"400\">\n" +
" <param name=\"movie\" value=\"http://yourname.com/flvplayer.swf\" />\n" +
" <param name=\"quality\" value=\"high\" />\n" +
" <param name=\"allowFullScreen\" value=\"true\" />\n" +
" <embed src=\"flvplayer.swf\" allowfullscreen=\"true\" flashvars=\"vcastr_file=videoDownload/"+getParams("param")+"&IsAutoPlay=1\" quality=\"high\" type=\"application/x-shockwave-flash\" width=\"960\" height=\"540\"></embed>\n" +
"</object>"
$("#object").append(txt)
}
console.log("参数param1:"+getParams("param"));//输出aa
</script>
<div id="object"></div>
</body>
</html>
6、创建枚举类,存储视频文件目录:
public enum VideoPath {
//存储地址以及代号
ONE(1,"C:\\Users\\yebing\\Desktop\\video1\\"),
TWO(2,"C:\\Users\\yebing\\Desktop\\video2\\"),
THREE(3,"C:\\Users\\yebing\\Desktop\\video3\\");
private int num;
private String name;
private VideoPath(int num, String name){
this.num = num;
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
7、创建获取视频目录控制器:
@RestController等同于@ResponseBody+@Controller,JSONObject为阿里fastjson包转换json的方法。
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
@RestController
public class RequireVideoPath {
/**
* 获取文件夹下所有文件
* @return
*/
@GetMapping("/VideoPath")
public static String requireVideoPath(){
String path = null;
String[] paths = null;
//使用枚举代替常量
File rootFile = new File(VideoPath.ONE.getName());
File[] files = rootFile.listFiles();
paths = new String[files.length];
for(int i =0;i<files.length;i++){
File childrenFile = files[i];
System.out.println(childrenFile.getPath());
paths[i] = childrenFile.getName();
}
System.out.println(JSONObject.toJSONString(paths));
path = JSONObject.toJSONString(paths);
return path;
}
public static void main(String[] args){
requireVideoPath();
}
}
8、创建视频播放类:
从httpServletResponse中获取servletOutputStream输出流,同时使用NIO流进行流的传输,最后千万记得关闭流,不然会导致内存泄漏等问题,保持这个好习惯。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
@Controller
public class VideoDownload {
@GetMapping("/videoDownload/{id}")
public void fileDownload(@PathVariable("id") String id, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
//响应文件流准备
File file = new File(VideoPath.ONE.getName()+id);
FileInputStream fileInputStream = null;
//response响应输出流
ServletOutputStream servletOutputStream = null;
//响应Http信息头准备
httpServletResponse.addHeader("Content-Disposition", "attachment;filename=\""+file.getName()+"\"");
httpServletResponse.addHeader("Content-Length",file.length()+"");
httpServletResponse.setContentType("application/octet-stream");
try{
//输出流信息准备
servletOutputStream = httpServletResponse.getOutputStream();
//文件流准备,打开NIO流管道
fileInputStream = new FileInputStream(file);
//调用方法
servletOutput(fileInputStream, servletOutputStream);
}catch (Exception e){
System.out.println("servletOutputStream异常!");
}finally{
try {
servletOutputStream.close();
fileInputStream.close();
} catch (IOException e) {
System.out.println("文件流关闭异常!");
}
}
}
public void servletOutput(FileInputStream fileInputStream, ServletOutputStream servletOutputStream){
FileChannel fileChannel = fileInputStream.getChannel();
try {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024*1024);
byte[] bytes = new byte[1024*1024];
int i = fileChannel.read(byteBuffer);
byteBuffer.flip();
while(i!=-1){
//如果缓冲区剩下字节数不足1024*1024个字节,则重新创建数组对象
if(byteBuffer.remaining()!=1024*1024){
bytes = new byte[byteBuffer.remaining()];
}
byteBuffer.get(bytes);
servletOutputStream.write(bytes);
byteBuffer.clear();
i = fileChannel.read(byteBuffer);
byteBuffer.flip();
}
servletOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
总结:
项目视频播放必须使用flv格式,这个是现代视频播放普遍使用的一种格式,flvplayer.swf插件可以网上下载用于前端播放flv格式视频。
前后端使用jquery的ajax实现前后端分离,可实现局部的刷新无需重新加载页面。