c# HTML5 Blob对象实现媒体播放功能
后台代码:
public ActionResult Video() { string filePath = @"D:\download\test.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-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileInfo.Name)); 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(); } }
前台代码:
html: <video id="video_player" width="660" height="364" controls="controls"></video> Js: //创建XMLHttpRequest对象 var xhr = new XMLHttpRequest(); //配置请求方式、请求地址以及是否同步 xhr.open('POST', 'Video', true); //设置请求结果类型为blob xhr.responseType = 'blob'; //请求成功回调函数 xhr.onload = function (e) { if (this.status == 200) {//请求成功 //获取blob对象 var blob = this.response; var video = document.getElementById('video_player'); //获取blob对象地址,并把值赋给容器 var obj_url = window.URL.createObjectURL(blob); video.src = obj_url; //video.play(); setTimeout("revokeUrl('" + obj_url + "')", "2000"); } }; xhr.send(); function revokeUrl(url) { window.URL.revokeObjectURL(url); }
看云吧 kanyun8.com