c#,.net,MVC,处理blob视频的播放
现在许多视频在线观看网站,你如果打开chrome查看其video标签,会发现它的src是一个以blob:开头的地址。可以看到他这里引入的并不是一个在线的视频存放地址,这样你通过爬虫脚本也无法下载该视频文件,通过一个new tab打开也于事无补,会提示你地址错误。
后端实现代码如下(示例):
public ActionResult Index()
{
return View();
}
public void Video()
{
string filePath = this.Server.MapPath("~/images/video/products/video.mp4");
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
if (fileInfo.Exists == true)
{
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.AddHeader("Content-Length", "" + fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
前端界面代码如下(示例):
<div>
<video id="video_player" width="660" height="364" controls="controls"></video>
</div>
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', '/AAAtest/Video', true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
if (this.status == 200) {
var blob = this.response;
var video = document.getElementById('video_player');
var obj_url = window.URL.createObjectURL(blob);
video.src = obj_url;
}
};
xhr.send();
function revokeUrl(url) {
window.URL.revokeObjectURL(url);
}
</script>
这样就可以得到以blob:开头的临时url地址,而且在向服务端请求时页隐藏了真实的视频地址。
|