Introduction
This article shows how to save an image into a database using a FileUpload control of ASP.NET.
To explain this article I will use the following procedure:
- Create a table in the database to store the image and some other relevant data by which I can fetch the image from the table.
- Create a website with a page that contains some controls like "textbox", "FileUpload" and "Button" in the design part of that page (.aspx).
- Write the code in the ".cs" file of that page to save the image in the database for the "button click" event.
The following are the detailed steps for the preceding procedure.
Step 1
Create a table named "Images" that will store the following:
- Roll number of a student
- Image of a student
- Date of image insertion
- CREATE TABLE dbo.Images(
- Roll_no varchar(12) primary key,
- img varbinary(max) ,
- img_date datetime
- )
Step 2
- Create a new empty Website named "ImageToBinary".
- Add a new Page named "Conversion.aspx".
Step 3
- Add the following 3 controls to the page:
- TextBox (For Roll number of student)
- FileUpload (For selecting the image)
- Button with Onclick event (For submit the image)
- Roll No.
- <asp:TextBox ID="txtrollno" runat="server">
- </asp:TextBox>
- <br />
- Select File
- <asp:FileUpload ID="FileUpload1" runat="server" />
- <br />
- <asp:Button ID="Button1" runat="server"
- Text="Convert" OnClick="Button1_Click" />
- Write the code to insert the image into the database on the click event of the button.
- protected void Button1_Click(object sender, EventArgs e)
- {
- if (!FileUpload1.HasFile) //Validation
- {
- Response.Write("No file Selected"); return;
- }
- else
- {
- string filename = FileUpload1.PostedFile.FileName;
-
- //convert the image into the byte
- byte[] imageByte = System.IO.File.ReadAllBytes(filename);
-
- //Insert the Data in the Table
- using (SqlConnection connection = new SqlConnection())
- {
- connection.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ToString();
-
- connection.Open();
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = connection;
-
- string commandText = "Insert into Images values (@Rollno,@image,getdate())";
-
- cmd.CommandText = commandText;
- cmd.CommandType = CommandType.Text;
- cmd.Parameters.Add("@image", SqlDbType.VarBinary);
- cmd.Parameters["@image"].Value = imageByte;
- cmd.Parameters.Add("@Rollno", SqlDbType.VarChar);
- cmd.Parameters["@Rollno"].Value = txtrollno.Text;
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- connection.Close();
-
- Response.Write("Data has been Added");
- }
- }
- }
Step 4
- Run the page that will be like:
- Fill in the roll number and click on the browse button to select the image.
- After selecting the image.
- Click on the Covert button to save the image.
Result: Now you can see that the image has been saved in the database in binary format.