locked
Display pdf file from sql database RRS feed

  • Question

  • User810354248 posted

    I worked out to insert pdf file to sql database as per code given below. I tried the following code but it is not working. The gridview shows the data correctly but odf is not displayed and no error.

    Protected Sub btn_Upload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_Upload.Click
            If FileToUpload.PostedFile Is Nothing OrElse String.IsNullOrEmpty(FileToUpload.PostedFile.FileName) OrElse FileToUpload.PostedFile.InputStream Is Nothing Then
                lit_Status.Text = "<br />Error - unable to upload file. Please try again.<br />"
            Else
                Using Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("subbaijuep").ConnectionString)
                    Try
                        Const SQL As String = "INSERT INTO [CRV] ([mid],[CRV_No], [DateTimeUploaded], [MIME], [BinaryData]) VALUES (@mid,@CRV_No, @DateTimeUploaded, @MIME, @BinaryData)"
                        Dim cmd As New SqlCommand(SQL, Conn)
                        cmd.Parameters.AddWithValue("@mid", idtxt.Text)
                        cmd.Parameters.AddWithValue("@CRV_No", crvno.Text + " dt " + crvdt.Text)
                        cmd.Parameters.AddWithValue("@MIME", FileToUpload.PostedFile.ContentType)
    
                        Dim imageBytes(FileToUpload.PostedFile.InputStream.Length) As Byte
                        FileToUpload.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length)
                        cmd.Parameters.AddWithValue("@BinaryData", imageBytes)
                        cmd.Parameters.AddWithValue("@DateTimeUploaded", DateTime.Now)
    
                        Conn.Open()
                        cmd.ExecuteNonQuery()
                        lit_Status.Text = "<br />File successfully uploaded - thank you.<br />"
                        Conn.Close()
                    Catch
                        Conn.Close()
                    End Try
                End Using
            End If
            lit_Status.Text = ""
        End Sub

    Now i want to display the inserted pdf file in asp.net page 

    i made a gridview and the contents are displayed on it by clicking the MID i want to display the pdf.

     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
           If Not IsPostBack Then
                BindGrid()
            End If
        End Sub
    Private Sub BindGrid()
            Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using con As New SqlConnection(constr)
                Using cmd As New SqlCommand()
                    cmd.CommandText = "select mId, CRV_No from CRV"
                    cmd.Connection = con
                    con.Open()
                    GridView1.DataSource = cmd.ExecuteReader()
                    GridView1.DataBind()
                    con.Close()
                End Using
            End Using
        End Sub
        Protected Sub View(ByVal sender As Object, ByVal e As EventArgs)
            Dim id As Integer = Integer.Parse(TryCast(sender, LinkButton).CommandArgument)
            Dim embed As String = "<object data=""{0}{1}"" type=""application/pdf"" width=""500px"" height=""600px"">"
            embed += "If you are unable to view file, you can download from <a href = ""{0}{1}&download=1"">here</a>"
            embed += " or download <a target = ""_blank"" href = ""http://get.adobe.com/reader/"">Adobe PDF Reader</a> to view the file."
            embed += "</object>"
            ltEmbed.Text = String.Format(embed, ResolveUrl("~/FileVB.ashx?Id="), id)
        End Sub
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField DataField="CRV_No" HeaderText="CRV" />
                    <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkView" runat="server" Text="View" OnClick="View" CommandArgument='<%# Eval("mId") %>'></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
                <asp:Literal ID="ltEmbed" runat="server" />


    Sunday, May 14, 2017 5:38 PM

Answers

  • User-271186128 posted

    Hi Baiju EP,

    I have tested your provide code, it is worked.
    Do you have any error message in your browser console(F12)?
    Could you show me your code in FileVB.ashx?
    Here is my code in ashx:

      Public Sub ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest
            Dim id As Integer = Integer.Parse(context.Request.QueryString("Id"))
            Dim bytes As Byte()
            Dim fileName As String, contentType As String
            Dim constr As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
            Using con As New SqlConnection(constr)
                Using cmd As New SqlCommand()
                    cmd.CommandText = "SELECT CRV_No, MIME, BinaryData FROM CRV WHERE Id=@Id"
                    cmd.Parameters.AddWithValue("@Id", id)
                    cmd.Connection = con
                    con.Open()
                    Using sdr As SqlDataReader = cmd.ExecuteReader()
                        sdr.Read()
                        bytes = DirectCast(sdr("BinaryData"), Byte())
                        contentType = sdr("MIME").ToString()
                        fileName = sdr("CRV_No").ToString()
                    End Using
                    con.Close()
                End Using
            End Using
    
            context.Response.Buffer = True
            context.Response.Charset = ""
            If context.Request.QueryString("download") = "1" Then
                context.Response.AppendHeader("Content-Disposition", Convert.ToString("attachment; filename=") & fileName)
            End If
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
            context.Response.ContentType = "application/pdf"
            context.Response.BinaryWrite(bytes)
            context.Response.Flush()
            context.Response.[End]()
        End Sub
    
    

    More details, you could check this article:

    https://www.aspsnippets.com/Articles/Retrieve-and-display-PDF-Files-from-database-in-browser-in-ASPNet.aspx

    Best regards,
    Dillion

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 15, 2017 6:55 AM