html5 Ajax 访问.net WebApi获取视频流

2018-06-22 07:58:20来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折


http://localhost//api/Test/GetVideo?filename=/GoodVideo/e36a144b-52cd-4174-93d2-cfc41aea6c1d.mp4 是API地址加上视频路径,此地址一般是动态获取
<video id="video" style="width:100%;" controls="controls" preload="preload" onerror="videoError(this)">
<source src="http://localhost//api/Test/GetVideo?filename=/GoodVideo/e36a144b-52cd-4174-93d2-cfc41aea6c1d.mp4" type="video/mp4"> 
</video>

src直接写入api地址,filename是对应服务器视频存储的地址。

后台对应代码

 //视频接口
        public HttpResponseMessage GetVideo(string filename)
        {
            var video = new VideoStream(filename);
            Action<Stream, HttpContent, TransportContext> send = video.WriteToStream;
            var response = Request.CreateResponse();
            response.Content = new System.Net.Http.PushStreamContent(send, new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4"));
            //调用异步数据推送接口  
            return response;
        }  
VideoStream 帮助类代码如下
  public class VideoStream
    {
        private readonly string _filename;

        public VideoStream(string filename)
        {
            _filename = HttpContext.Current.Server.MapPath("~" + filename); ;
        }
        public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                var buffer = new byte[65536];

                using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    var length = (int)video.Length;
                    var bytesRead = 1;

                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }
            }
            catch (HttpException ex)
            {
                return;
            }
            finally
            {
                outputStream.Close();
            }
        }  
    }

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:LoadRunner 12下载和安装教程

下一篇:基于ASP.NET 4.0开发的微商城系统OdnShop,开源发布