I'm am looking for the posted contents as they come into the server, but
(IMPORTANTLY) before they have been completely sent. Specifically, I need
to let users upload ~ 1gb files so I need to grab the posted file bytes as
they are streaming into the server and save it to disk.
Can I do this by wiring an event to the BeginRequest in the Init event of a
module? Will the code below work? If so, how do I ensure that all of the
posted file bytes do not go into memory? Will the act of reading the bytes
ensure that the bytes do not go into memory as the request is sent on to the
page handler?
'sorry for the vb, forced to use this language
Public Sub Init(ByVal app As HttpApplication) Implements IHttpModule.Init
AddHandler app.BeginRequest, New EventHandler(AddressOf
Me.OnBeginRequest)
End Sub
Public Sub OnBeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim ctx As HttpContext = CType(sender, HttpApplication).Context
If ctx.Request.Files.Count > 0 Then
Dim fs As New FileStream(Path.Combine("c:\uploads",
Path.GetFileName(ctx.Request.Files(0).FileName)), FileMode.Create)
Dim br As New BinaryReader(ctx.Request.Files(0).InputStream)
Dim bw As New BinaryWriter(fs)
Dim size As Integer = 1024
Dim position As Integer
Do
If position + size > br.BaseStream.Length Then
size = Convert.ToInt32(br.BaseStream.Length) - position
End If
bw.Write(br.ReadBytes(size))
position += size
Loop Until position >= ctx.Request.Files(0).ContentLength
bw.Close()
br.Close()
fs.Close()
End If
End Sub