Save binary image in Database using Entity Framework in ASP.Net

Last Reply 23 days ago By pandeyism

Posted 23 days ago

I want to save image into database using entity framework without mvc.

I have tried bt it wont worked. Plz Help me out from this problem.

Below I have attached file which i have tried

.aspx code

<div style="float:left">
  <table>
      <tr >
          <td style="padding-left:5px">
              <div style="float:left">
                   <asp:Image ID="Image1" ImageUrl="http://localhost:9002/Images/pup.jpg" runat="server" class="img-circle" />
              </div>
          </td>         
      </tr>
      </table>
      </div>
      <div style="float:none">          
          <asp:Label ID="lblAllow" runat="server" Text="Allowed file types: TIF, PNG, JPG" ></asp:Label><br />
          <asp:FileUpload ID="FileUpload1" runat="server" UploadedFilesRendering="BelowFileInput"/><br /><br />
          <div style="text-align:center">
              <Telerik:RadButton ID="RadBtnUpload" runat="server" Text="Upload Selected" skin="Windows7" style="align-self:center" OnClick="RadBtnUpload_Click">
                  <Icon PrimaryIconCssClass="RadBtnUpload" />
              </Telerik:RadButton>
           </div>         
           <asp:RegularExpressionValidator ID="RegularExpressionValidator3" ValidationExpression="([a-zA-Z0-9\s_\\.\-:])+(.png|.PNG|.jpg|.JPG|.tif|.TIF)$"
           ControlToValidate="FileUpload1" runat="server" ForeColor="Red" ErrorMessage="Only JPG, PNG, TIF allowded." ShowMessageBox="true"
           Display="Dynamic" />
       </div> 
</div>

.asp.cs code

        protected void RadBtnUpload_Click(object sender, EventArgs e)
        {
            string folderPath = Server.MapPath("~/Forms/Uploads/");
            if (!Directory.Exists(folderPath))
            {
               Directory.CreateDirectory(folderPath);
            }
            FileUpload1.SaveAs(folderPath + Path.GetFileName(FileUpload1.FileName));
            Image1.ImageUrl = "~/Forms/Uploads/" + Path.GetFileName(FileUpload1.FileName);
            EmployeePortal.Models.NCI.NCIEntities ent = EmployeePortal.Models.ClsNCIUtil.GetNCIEntity(Session["CustomerID"].ToString());
            using (ent)
            {
                EmployeePortal.Models.NCI.EmployeeImage eimg = ent.EmployeeImages.FirstOrDefault(a => a.EmployeeId == empno);//&& a.CustomerId == customerId);
                if (FileUpload1.HasFile)
                {
                    var img= (from a in ent.EmployeeImages where a.EmployeeId == empno select a.EmpImage);
                    byte[] 
                        FileUpload1 = eimg.EmpImage;
              
                    ent.SaveChanges();
                }
            }       

plz help me....

CREATE TABLE [dbo].[EmployeeImage](
    [SrNo] [int] IDENTITY(1,1) NOT NULL,
    [EmployeeId] [int] NULL,
    [CustomerId] [int] NULL,
    [EmpImage] [image] NULL,
    [LastModifiedDate] [datetime] NULL,
    [LastModifiedUser] [nvarchar](25) NULL,
    [LastModifiedDescription] [varchar](200) NULL,
 CONSTRAINT [PK_EmployeeImage] PRIMARY KEY CLUSTERED
(
    [SrNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

 

Posted 23 days ago Modified on 23 days ago

Hi JennyD6856,

Please refer below sample.

Using below article i have created sample, So you can refer below article for details.

Display Binary Image from database in ASP.Net GridView control using C# and VB.Net

HTML

<div>
    <asp:FileUpload ID="fuInsert" runat="server" />
    <br />
    <asp:Button ID="btnInsert" runat="server" Text="Insert" OnClick="Insert" />
</div>

Namespaces

C#

using System;
using System.IO;
using dbFilesModel;

VB.Net

Imports dbFilesModel
Imports System.IO

Code

C#

protected void Insert(object sender, EventArgs e)
{
    dbFilesEntities entities = new dbFilesEntities();
    string folderPath = Server.MapPath("~/Files/");
    if (!Directory.Exists(folderPath))
    {
        Directory.CreateDirectory(folderPath);
    }
    fuInsert.SaveAs(folderPath + Path.GetFileName(fuInsert.FileName));
    Stream fs = fuInsert.PostedFile.InputStream;
    BinaryReader br = new BinaryReader(fs);
    byte[] bytes = br.ReadBytes((Int32)fs.Length);
    tblFile file = new tblFile
    {
        Name = fuInsert.FileName,
        ContentType = fuInsert.PostedFile.ContentType,
        Data = bytes
    };
    entities.AddTotblFiles(file);
    entities.SaveChanges();
}

VB.Net

Protected Sub Insert(ByVal sender As Object, ByVal e As EventArgs)
    Dim entities As dbFilesEntities = New dbFilesEntities()
    Dim folderPath As String = Server.MapPath("~/Files/")

    If Not Directory.Exists(folderPath) Then
        Directory.CreateDirectory(folderPath)
    End If

    fuInsert.SaveAs(folderPath & Path.GetFileName(fuInsert.FileName))
    Dim fs As Stream = fuInsert.PostedFile.InputStream
    Dim br As BinaryReader = New BinaryReader(fs)
    Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Int32))
    Dim file As tblFile = New tblFile With {
        .Name = fuInsert.FileName,
        .ContentType = fuInsert.PostedFile.ContentType,
        .Data = bytes
    }
    entities.AddTotblFiles(file)
    entities.SaveChanges()
End Sub