Uploaded file using VB.Net is empty in ASP.Net

makumbi
 
on Jul 15, 2022 01:52 AM
350 Views

When i try to upload a file the remains empty when i click on upload.

If FileUpload1.HasFile Then
Protected Sub Upload(ByVal sender As Object, ByVal e As EventArgs)
    Dim bytes As Byte()
    Using br As BinaryReader = New BinaryReader(FileUpload1.PostedFile.InputStream)
        bytes = br.ReadBytes(FileUpload1.PostedFile.ContentLength)
    End Using
 
    If FileUpload1.HasFile Then
        Dim fs As Stream = FileUpload1.PostedFile.InputStream
        Dim br As New BinaryReader(fs)
        '  Dim bytes As Byte() = br.ReadBytes(fs.Length)
        Using Cont As New SqlConnection(constr)
            Cont.Open()
            Using cmd As New SqlCommand
                cmd.Connection = Cont
                cmd.CommandType = CommandType.StoredProcedure
                cmd.CommandText = "GetPhotoinsert"
                cmd.Parameters.Add("@nm", SqlDbType.NVarChar).Value = Path.GetFileName(FileUpload1.PostedFile.FileName)
                cmd.Parameters.Add("@ct", SqlDbType.NVarChar).Value = FileUpload1.PostedFile.ContentType
                cmd.Parameters.Add("@p", SqlDbType.Binary).Value = bytes
                cmd.Parameters.AddWithValue("@n", Names.Text)
                cmd.ExecuteReader()
                Cont.Close()
 
                Exit Sub
            End Using
        End Using
    End If
 
    Response.Redirect(Request.Url.AbsoluteUri)
End Sub

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 15, 2022 01:56 AM

Hi makumbi,

Replace with below code.

Protected Sub Upload(ByVal sender As Object, ByVal e As EventArgs)
    If FileUpload1.HasFile Then
        Dim fs As Stream = FileUpload1.PostedFile.InputStream
        Dim br As New BinaryReader(fs)
        Dim bytes As Byte() = br.ReadBytes(DirectCast(fs.Length, Long))
        Using Cont As New SqlConnection(constr)
            Cont.Open()
            Using cmd As New SqlCommand
                cmd.Connection = Cont
                cmd.CommandType = CommandType.StoredProcedure
                cmd.CommandText = "GetPhotoinsert"
                cmd.Parameters.Add("@nm", SqlDbType.NVarChar).Value = Path.GetFileName(FileUpload1.PostedFile.FileName)
                cmd.Parameters.Add("@ct", SqlDbType.NVarChar).Value = FileUpload1.PostedFile.ContentType
                cmd.Parameters.Add("@p", SqlDbType.Binary).Value = bytes
                cmd.Parameters.AddWithValue("@n", Names.Text)
                cmd.ExecuteNonQuery()
                Cont.Close()
                Exit Sub
            End Using
        End Using
    End If

    Response.Redirect(Request.Url.AbsoluteUri)
End Sub