Hi,
if you want to store your file in sql server database, you can use Varbinary type for this.
you can try following piece of code and table structure for your purpose, I hope it matches your requirements.
Table structure:
CREATE TABLE [dbo].[PdfFiles](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Type] [varchar](50) NULL,
[Data] [varbinary](max) NULL
) ON [PRIMARY]
Code on button click:
protected void btnUpload_Click(object sender, EventArgs e)
{
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string type = String.Empty;
if (!FileUpload1.HasFile)
{
Label2.ForeColor = System.Drawing.Color.Red;
Label2.Text = "Please Select a File";
}
else if (FileUpload1.HasFile)
{
switch (ext)
{
case ".pdf":
type = "application/pdf";
break;
case ".txt":
type = "application/txt";
break;
case ".docx":
type = "application/docx";
break;
}
if (type != string.Empty)
{
SqlConnection conn = new SqlConnection(con);
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string query = "insert into PdfFiles (Name,type,data)" + " values (@Name, @type, @Data)";
SqlCommand com = new SqlCommand(query, conn);
com.Parameters.AddWithValue("@Name", filename);
com.Parameters.AddWithValue("@type", type);
com.Parameters.AddWithValue("@Data", bytes);
conn.Open();
com.ExecuteNonQuery();
conn.Close();
Label2.ForeColor = System.Drawing.Color.Green;
Label2.Text = "File Uploaded Successfully";
}
else
{
Label2.ForeColor = System.Drawing.Color.Red;
Label2.Text = "Please select a pdf/txt/word file";
}
}
}
Happy coding :)