In this blog, we will learn how to save the files in the database table. We will make a Web Application. It is a secure way to save the data files/images in the database in the table.
Let’s start.
Database part Work
- First, we create a table in SQL database.
Eg,
- CREATE TABLE [dbo].[tbdata](
- [Blob] [varbinary](max) NOT NULL,
- [Name] [nvarchar](256) NULL,
- [Contenttype] [nvarchar](256) NULL
- ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Visual Studio
- Open Visual Studio, select File >New > Website
- Name it, as you want. My Application’s name is SampleWeb.
- First of all, open Solution Explorer and right click on ( Website Name) > Add > Add New Item > select Web Form:
- Add the file uploader, label and button in Default.aspx page:
Eg,- <asp:FileUpload ID="FU1" runat="server" /> <br /> <br />
- <asp:LinkButton ID="lb1" runat="server" Text="Submit" OnClick="lb1_Click" /> <br /><br />
- <asp:Label id="Label1" runat="server" />
- Add the code on Default.aspx.cs page:
Eg,
- protected void lb1_Click(object sender, EventArgs e) {
- if (FU1.HasFile) {
- try {
- string content_type = FU1.PostedFile.ContentType;
- string filename = FU1.PostedFile.FileName.ToLower();
- SqlConnection conn;
- SqlCommand cmd = new SqlCommand();
- conn = new SqlConnection("Data Source=DESKTOP-C4AN6J2\\SQLEXPRESS;Initial Catalog=test; Integrated Security=true;");
- conn.Open();
- BinaryReader br = new BinaryReader(FU1.PostedFile.InputStream);
- Byte[] bytes = br.ReadBytes((Int32) FU1.PostedFile.InputStream.Length);
- cmd.CommandText = "Insert into tbdata (Blob,Name,Contenttype)values( @bytes,@Name,@Contenttype)";
- cmd.Connection = conn;
- cmd.Parameters.AddWithValue("@bytes", bytes);
- cmd.Parameters.AddWithValue("@Name", filename);
- cmd.Parameters.AddWithValue("@Contenttype", content_type);
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- cmd.Connection.Close();
- Label1.Text = "Uploaded Sucessfully";
- } catch {
- Label1.Text = "Not Uploaded Sucessfully";
- }
- } else Label1.Text = "No Upload";
- }