zoukankan      html  css  js  c++  java
  • html5 Ajax 访问.net WebApi获取视频流

    
    
    http://localhost//api/Test/GetVideo?filename=/GoodVideo/e36a144b-52cd-4174-93d2-cfc41aea6c1d.mp4 是API地址加上视频路径,此地址一般是动态获取
    <video id="video" style="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();
                }
            }  
        }
  • 相关阅读:
    检查所有资产的剩余折旧年限
    如何返回standard API 的错误信息
    Host concurrent的建立方法
    Project的目录结构
    计划外折旧(unplanned deprn)API开发例程
    UML学习笔记
    ASP.Net2.0使用Log4Net(二)
    NBear学习笔记(一)
    ASP.Net2.0使用Log4Net(一)
    ASP.net前后台调用
  • 原文地址:https://www.cnblogs.com/jiezi/p/9104320.html
Copyright © 2011-2022 走看看