0

I'm trying to download a file from an SQL Server table. I am using a GridView. Whenever I try to download a file, I get a corrupted file.

I am using ASP.NET and VB.NET with SQL Server 2012 Express.

Any ideas why ?

Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged

    Dim ContentID = Convert.ToInt32(GridView1.SelectedRow.Cells(1).Text)
    Dim ContentName = GridView1.SelectedRow.Cells(2).Text
    Dim ContentType = GridView1.SelectedRow.Cells(3).Text

    lblContentName.Text = "[ " + ContentName + " ]"
    lblContentName.Visible = True


End Sub

Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)


    Dim cn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")

    If e.CommandName = "Download" Then
        Dim filename As String = String.Empty
        Dim id As Integer = Convert.ToInt32(e.CommandArgument)
        Dim cmd As New SqlCommand("SELECT content_name,content_type,content_data FROM content WHERE content_id = " & id, cn)
        cn.Open()
        Dim dr As SqlDataReader = cmd.ExecuteReader
        Dim bytes As Byte()
        dr = cmd.ExecuteReader()
        If dr.Read() Then
            filename = dr("content_name").ToString()
            Response.ContentType = dr("content_type").ToString()
            Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
            bytes = DirectCast(dr("content_file"), Byte())
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Response.BinaryWrite(bytes)
            Response.Flush()
            Response.[End]()
        End If
    End If
End Sub

Private Sub BindGrid()
    Dim constr As String = ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand()
            cmd.CommandText = "SELECT content_id, content_name FROM content"
            cmd.Connection = con
            con.Open()
            GridView1.DataSource = cmd.ExecuteReader()
            GridView1.DataBind()
            con.Close()
        End Using
    End Using

End Sub

 Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindGrid()
        End If
    End Sub
4

0 回答 0