本人在做项目的时候,有个功能需求需要播放云上的视频和本地磁盘里的视频,播放云上的视频有url直接就能播放,但是播放本地的视频涉及到浏览器跨域的问题,在网上找了很多,但都不能解决我的问题,最后想到了构建流的方式在服务器上播放本地视频。
下面是我在服务器上播放本地视频的效果图
先贴上html5代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- controlslist="nodownload" 去掉下载按钮 -->
<!--<video controls="true" controlslist="nodownload"></video>-->
<video controls="true" ></video>
</body>
<script type="text/javascript">
//禁用掉video的右键菜单
var video=document.getElementsByTagName("video")[0];
video.oncontextmenu=function(){
return false;
}
var url="/Users/lijunming/Desktop/demo.mp4"; //电脑上视频文件的绝对路径
video.src="showVideo?fileName="+url; //告诉服务器要播放视频文件的路径
</script>
</html>
接下来就是服务器根据video标签推送的本地视频url,响应视频流给浏览器
package com.sinosoft.easyrecordhs.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
/**
* Created by lijunming
* on date 2018-08-08
* time 13:07
*/
@RestController
public class RequestController {
/**
* 根据本地图片全路径,响应给浏览器1个图片流
*/
@RequestMapping("/showImage")
public void showImage(HttpServletResponse response, @RequestParam("fileName")String fileName) {
show(response,fileName,"image");
}
/**
* 根据本地视频全路径,响应给浏览器1个视频
*/
@RequestMapping("/showVideo")
public void showVideo(HttpServletResponse response, @RequestParam("fileName")String fileName) {
show(response,fileName,"video");
}
/**
* 响应文件
* @param response
* @param fileName 文件全路径
* @param type 响应流类型
*/
public void show(HttpServletResponse response, String fileName,String type){
try{
FileInputStream fis = new FileInputStream(fileName); // 以byte流的方式打开文件
int i=fis.available(); //得到文件大小
byte data[]=new byte[i];
fis.read(data); //读数据
response.setContentType(type+"/*"); //设置返回的文件类型
OutputStream toClient=response.getOutputStream(); //得到向客户端输出二进制数据的对象
toClient.write(data); //输出数据
toClient.flush();
toClient.close();
fis.close();
}catch(Exception e){
e.printStackTrace();
System.out.println("文件不存在");
}
}
}