akhter says:
string
imageUrldoc =
"datadoc:image/jpg;base64,"
+ Convert.ToBase64String((
byte
[])dr1[
"DataDoc"
]);
The datadoc must be data.
Pls refer below updated code sample.
HTML
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<hr />
<asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Image Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="img" runat="server" Height="100px" Width="100px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Docx">
<ItemTemplate>
<asp:Image ID="img1" runat="server" Height="100px" Width="100px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
C#
using System.IO;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT Id,Name,Data,Data as 'DataDoc' FROM tblFiles", conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
}
}
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView dr = (DataRowView)e.Row.DataItem;
string imageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])dr["Data"]);
(e.Row.FindControl("img") as System.Web.UI.WebControls.Image).ImageUrl = imageUrl;
//DataRowView dr1 = (DataRowView)e.Row.DataItem;
string imageUrldoc = "data:image/jpg;base64," + Convert.ToBase64String((byte[])dr["DataDoc"]);
(e.Row.FindControl("img1") as System.Web.UI.WebControls.Image).ImageUrl = imageUrldoc;
}
}
protected void Upload(object sender, EventArgs e)
{
byte[] bytes;
using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
bytes = br.ReadBytes(FileUpload1.PostedFile.ContentLength);
}
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
string sql = "INSERT INTO tblFiles VALUES(@Name, @ContentType, @Data)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Name", Path.GetFileName(FileUpload1.PostedFile.FileName));
cmd.Parameters.AddWithValue("@ContentType", FileUpload1.PostedFile.ContentType);
cmd.Parameters.AddWithValue("@Data", bytes);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
Screenshot