How do I stream a video file using ASP.NET MVC?

前端 未结 3 1393
难免孤独
难免孤独 2021-02-13 22:21

I am developing a web site where people can access audio and video files. I have the code for downloading the files, which consists of two action methods as follows...



        
3条回答
  •  醉梦人生
    2021-02-13 22:47

    Controller

    Imports System.Web.Mvc
    
    Namespace Controllers
        Public Class HomeController
            Inherits Controller
    
            Function Index() As ActionResult
                Return View()
            End Function
    
            Sub movie(id As Integer) 'As ActionResult
    
                Dim fm As String = "D:\Downloads\Rhoma Irama  Riza Umami - Suratan (Official Music Video).mp4"
    
                If id = 2 Then fm = "D:\Downloads\JERA riza umami   lagu dangdut   YouTube.mp4"
                If id = 3 Then fm = "D:\Downloads\FTV Trans TV CINTANYA ANAK HITS KEKINIAN RIDWAN GHANI.mp4"
    
                Dim fi As New IO.FileInfo(fm)
                Dim fs As IO.FileStream = IO.File.OpenRead(fm)
                Dim buff_size As Integer = 1048576 '1Mb buffering
                Dim buff(buff_size) As Byte, max_l As Integer = fs.Length - 1
    
                If Not Request.ServerVariables("HTTP_RANGE") Is Nothing Then
    
                    Dim r() As String = Request.ServerVariables("HTTP_RANGE").Split("=")
                    Dim s() As String = r(1).Split("-")
                    Dim bs As Integer = 0, be As Integer = 0, l As Integer = 0
    
                    If IsNumeric(s(0)) Then bs = s(0)
                    If IsNumeric(s(1)) Then be = s(1)
    
                    If bs >= 0 And bs <= max_l Then
    
                        Response.StatusCode = 206
                        Response.ContentType = "video/" & fi.Extension
                        Response.AddHeader("Accept-Ranges", "0-" & max_l)
                        Response.AddHeader("Content-Range", "bytes " & bs & "-" & bs + buff_size & "/" & max_l)
                        Response.AddHeader("Content-Length", buff_size)
    
                        fs.Position = bs
                        l = fs.Read(buff, 0, buff.Length)
                        If l > 0 Then Response.OutputStream.Write(buff, 0, buff.Length)
    
                    End If
    
                End If
    
            End Sub
        End Class
    End Namespace
    

    VIEWS (I use Razor)

    
        
        
        
          
    
    

提交回复
热议问题