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);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM