Upload a file using fileupload using asp.net


In this  blog I have taken one fileupload control and one simple asp button control, the html code is given below
 
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="StoreFileInDataBase.aspx.cs" Inherits="StoreFileInDataBase" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server"
        Text="Upload" onclick="Button1_Click" />
 
</asp:Content>
I have one database table named filecontent to store file, like 
 
create table filecontent
(
id int,
[filename] nvarchar(100),
filetext text
)

Use bellow code to upload you file in to database table, this bellow code i have used ado.net entity framework to store to and retrieve data from database
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class StoreFileInDataBase : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

 
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            uploadfile(1, FileUpload1.FileName, FileUpload1.PostedFile.InputStream);
        }
    }
    private void uploadfile(int id,string filename,System.IO.Stream filedata)
    {
        string constring="Data Source=MADHUSUDAN;Initial Catalog=test;User ID=sa;Password=raghava";
        SqlConnection con = new SqlConnection(constring);
        System.IO.StreamReader reader = new System.IO.StreamReader(filedata);
        con.Open();
        string data = reader.ReadToEnd();
        SqlCommand com = new SqlCommand("INSERT INTO filecontent(id,filename,filetext) VALUES (" + id + ",'" + filename + "','" + data + "')",con);
        com.ExecuteNonQuery();
        con.Close();
    }
Ebook Download
View all
Learn
View all