Upload and preview images and save in Database using C#, VB.Net and jQuery in ASP.Net

Last Reply 6 days ago By kalpesh

Posted 8 days ago

I have a requirement where i need to upload and display multiple image simultaneously while uploading and saving all to oracle database. I tried a lot but not full fill the exact requirement.

Any Example or help how to achieve it.

 

 

You are viewing reply posted by: kalpesh 6 days ago.
Posted 6 days ago

Refer the below Sample code for your reference implement saving logic by Oracle code as per your code logic.

SQL

CREATE TABLE [dbo].[tblFiles](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) NULL,
	[ContentType] [varchar](50) NULL,
	[Data] [varbinary](max) NULL,
 CONSTRAINT [PK_tblFiles] PRIMARY KEY CLUSTERED 
(
	[Id] 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]

C#

ImageFiles.cs

// Class Image Files  
public class ImageFiles
{
    public string Name { get; set; }
    public byte[] Data { get; set; }
}

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style>
        input[type="file"]
        {
            display: block;
        }
        .imageThumb
        {
            max-height: 75px;
            border: 2px solid;
            margin: 10px 10px 0 0;
            padding: 1px;
        }
    </style>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            $("[id*=files]").click(function () {
                if (window.File && window.FileList && window.FileReader) {
                    $("#files").on("change", function (e) {
                        var files = e.target.files,
                    filesLength = files.length;
                        for (var i = 0; i < filesLength; i++) {
                            var f = files[i]
                            var fileReader = new FileReader();
                            fileReader.onload = (function (e) {
                                var file = e.target;
                                $("<img></img>", {
                                    class: "imageThumb",
                                    src: e.target.result,
                                    title: file.name,
                                    name: 'test'
                                }).insertAfter("#files");
                            });
                            fileReader.readAsDataURL(f);
                        }
                    });
                } else { alert("Your browser doesn't support to File API") }
            });
        });
            
    </script>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <h2>
            preview multiple images before upload using jQuery</h2>
        <input type="file" id="files" name="files[]" multiple />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
        <br />
        <br />
        <asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Image Width="100px" Height="100px" ID="Image2" runat="server" ImageUrl='<%# "data:image/png;base64," + Convert.ToBase64String((byte[])Eval("Data")) %>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        // Bind Grid on Page load
        this.BindGrid();
    }
}

private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["ConStr3"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select Name,Data from tblFiles";
            cmd.Connection = con;
            con.Open();
            List<ImageFiles> imagefiles = new List<ImageFiles>();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    imagefiles.Add(new ImageFiles
                    {
                        Name = sdr["Name"].ToString(),
                        Data = (byte[])sdr["Data"]
                    });
                }
            }
            gvImages.DataSource = imagefiles;
            gvImages.DataBind();
            con.Close();
        }
    }
}

protected void btnUpload_Click(object sender, EventArgs e)
{
    string contentType = "image/png";
    string fileName = string.Empty;
    for (int i = 0; i < Request.Files.Count; i++)
    {
        HttpPostedFile postedFile = Request.Files[i];
        if (postedFile.ContentLength > 0)
        {
            fileName = Path.GetFileName(postedFile.FileName);
            Stream fs = postedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);

            // Call saving method by accessing the parameters
            SaveImageFile(fileName, contentType, bytes);
        }

    }
    this.BindGrid();
}

// function created to save details in sql database
private void SaveImageFile(string fileName, string contentType, Byte[] bytes)
{
    string constring = ConfigurationManager.ConnectionStrings["ConStr3"].ConnectionString;
    SqlConnection con = new SqlConnection(constring);
    SqlCommand cmd = new SqlCommand("insert into tblFiles (Name, ContentType, Data) values (@Name, @ContentType, @Data)", con);
    cmd.CommandType = CommandType.Text;
    con.Open();
    cmd.Parameters.AddWithValue("@Name", SqlDbType.VarChar).Value = fileName;
    cmd.Parameters.AddWithValue("@ContentType", SqlDbType.VarChar).Value = contentType;
    cmd.Parameters.AddWithValue("@Data", SqlDbType.VarBinary).Value = bytes;
    cmd.ExecuteNonQuery();
    con.Close();
}

VB.Net

ImageFiles.vb

Public Class ImageFiles

    Public Property Name As String

    Public Property Data As Byte()
End Class

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <style>
        input[type="file"]
        {
            display: block;
        }
        .imageThumb
        {
            max-height: 75px;
            border: 2px solid;
            margin: 10px 10px 0 0;
            padding: 1px;
        }
    </style>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            $("[id*=files]").click(function () {
                if (window.File && window.FileList && window.FileReader) {
                    $("#files").on("change", function (e) {
                        var files = e.target.files,
                    filesLength = files.length;
                        for (var i = 0; i < filesLength; i++) {
                            var f = files[i]
                            var fileReader = new FileReader();
                            fileReader.onload = (function (e) {
                                var file = e.target;
                                $("<img></img>", {
                                    class: "imageThumb",
                                    src: e.target.result,
                                    title: file.name,
                                    name: 'test'
                                }).insertAfter("#files");
                            });
                            fileReader.readAsDataURL(f);
                        }
                    });
                } else { alert("Your browser doesn't support to File API") }
            });
        });
            
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <h2>
            preview multiple images before upload using jQuery</h2>
        <input type="file" id="files" name="files[]" multiple />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
        <br />
        <br />
        <asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Image Width="100px" Height="100px" ID="Image2" runat="server" ImageUrl='<%# "data:image/png;base64," & Convert.ToBase64String(CType(Eval("Data"), Byte())) %>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not Me.IsPostBack Then
        'Bind Grid on Page load
        Me.BindGrid()
    End If
End Sub

Private Sub BindGrid()
    Dim constr As String = ConfigurationManager.ConnectionStrings("ConStr3").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand()
            cmd.CommandText = "select Name,Data from tblFiles"
            cmd.Connection = con
            con.Open()
            Dim imagefiles As List(Of ImageFiles) = New List(Of ImageFiles)()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    imagefiles.Add(New ImageFiles With {.Name = sdr("Name").ToString(), .Data = CType(sdr("Data"), Byte())})
                End While
            End Using 
            gvImages.DataSource = imagefiles
            gvImages.DataBind()
            con.Close()
        End Using
    End Using
End Sub

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim contentType As String = "image/png"
    Dim fileName As String = String.Empty
    For i As Integer = 0 To Request.Files.Count - 1
        Dim postedFile As HttpPostedFile = Request.Files(i)
        If postedFile.ContentLength > 0 Then
            fileName = Path.GetFileName(postedFile.FileName)
            Dim fs As Stream = postedFile.InputStream
            Dim br As BinaryReader = New BinaryReader(fs)
            Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Int32))
            'Call saving method by accessing the parameters
            SaveImageFile(fileName, contentType, bytes)
        End If
    Next

    Me.BindGrid()
End Sub

'function created to save details in sql database
Private Sub SaveImageFile(ByVal fileName As String, ByVal contentType As String, ByVal bytes As Byte())
    Dim constring As String = ConfigurationManager.ConnectionStrings("ConStr3").ConnectionString
    Dim con As SqlConnection = New SqlConnection(constring)
    Dim cmd As SqlCommand = New SqlCommand("insert into tblFiles (Name, ContentType, Data) values (@Name, @ContentType, @Data)", con)
    cmd.CommandType = CommandType.Text
    con.Open()
    cmd.Parameters.AddWithValue("@Name", SqlDbType.VarChar).Value = fileName
    cmd.Parameters.AddWithValue("@ContentType", SqlDbType.VarChar).Value = contentType
    cmd.Parameters.AddWithValue("@Data", SqlDbType.VarBinary).Value = bytes
    cmd.ExecuteNonQuery()
    con.Close()
End Sub

Screenshot

 

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html