Dharam Rai
Dharam Rai

Reputation: 81

How to retireive image from database in gridview without using file path

I have a module to upload file into my sqlserver database, where I have field like FName:varchar for filename, ContentType:nvarchar for FileType, and a Data:varbinary for actual data. So now I am able to retrive it in the gridview using BoundField which only displays the name of the file I uploaded, but what I actually want is to recognise the file from the database and if it is an image file then it should display that image in the gridview and if it is a file other than image then let it display only file name. Note I don't want to use folder to upload file and to retrieve it using file path. Would anyone has a similar experience to share please:

<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
    AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="File Name"/>
        <asp:TemplateField ItemStyle-HorizontalAlign = "Center">
            <ItemTemplate>
                <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
                    CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Code Behind:

protected void Upload(object sender, EventArgs e)
{
    string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
    string contentType = FileUpload1.PostedFile.ContentType;
    using (Stream fs = FileUpload1.PostedFile.InputStream)
    {
        using (BinaryReader br = new BinaryReader(fs))
        {
            byte[] bytes = br.ReadBytes((Int32)fs.Length);
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                string query = "insert into tblFiles values (@Name, @ContentType, @Data)";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@Name", filename);
                    cmd.Parameters.AddWithValue("@ContentType", contentType);
                    cmd.Parameters.AddWithValue("@Data", bytes);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
    }

}

Upvotes: 0

Views: 531

Answers (1)

Krishna
Krishna

Reputation: 1985

You need to use ContentType to decide how to show the data

<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000" OnRowDataBound="GridView1_RowDataBound"
    AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="File Name"/>
        <asp:TemplateField ItemStyle-HorizontalAlign = "Center">
            <ItemTemplate>
                <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
                    CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
                <img runat="server" id="imgData" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

in the row data bound decide what to do

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    LinkButton lnkButton = (LinkButton)e.Row.Cells[1].FindControl("lnkDownload");
                    HtmlImage img = (HtmlImage)e.Row.Cells[1].FindControl("imgData");
                    if (DataBinder.Eval(e.Row.DataItem, "ContentType").ToString().Contains("image"))//like image/jpeg
                    {
                        lnkButton.Visible = false;
                        img.Visible = true;
                        img.Src = "data:image/png;base64," + Convert.ToBase64String((byte[])DataBinder.Eval(e.Row.DataItem,"Data"));
                    }
                    else
                    {
                        lnkButton.Visible = true;
                        img.Visible = false;
                    }
                }
            }

Upvotes: 1

Related Questions