Browse/Upload Option in C#.NET For Uploading Files/Images in Database

Introduction

Browse or upload option is one of the most necessary feature of websites like photography, images, e books etc. So here am showing you on of the easiest path to create a browse option for your application or website.
There are three steps in creating a browse/upload option for your website, application, portal and so on.

image 1.jpg

Step 1

In SQL Server:

First of all we need to create a database in SQL Server, so for that we can define the values of attributes like this; for example: for images, we need to create something like:

Column     Data Type
    Img          image

image 2.jpg

[Full Table Page]

image 3.jpg
[Table]

Step 2

In Visual Studio:

Use the following procedure to create a sample in Visual Studio:

  1. Open the Tool Box
  2. File uploads (from TOOL box):
    • In standard tool option

      image 6.jpg

  3. Put a BUTTON (Upload)
  4. On a button click event
    • now click on the browse button option
    • it will generate a .cs file

Step 3

Coding

The following is the code for the .cs file:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Configuration;

using System.Data.SqlClient;

 

public partial class profile : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        string imagebyte;

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ABC"].ConnectionString);

        con.Open();

 

        if (FileUpload1.HasFile)

        {

            if (FileUpload1.PostedFile.ContentType == "image/jpg")

            {

                if (FileUpload1.PostedFile.ContentLength < 102400)

                {

                    int Length = FileUpload1.PostedFile.ContentLength;

                    Image.InputStream.Read(imagebyte, 0, Length);

                    SqlCommand cmd = new SqlCommand("insert into Signup(Image) values(@image)", con);

                    cmd.Parameters.Add("@image", imagebyte);

                    cmd.ExecuteNonQuery();

                    Label1.Text = ("Insert");

                }

                else

                {

                    Label1.Text = ("SelectFile");

                }

            }

        }

    }

}


Example

 

image 7.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all