In this example I am storing files like word document, text file and excel files into database and retrieving back from database and saving back into a folder.
So lets start creating a Table in SQL Server database in which we are going store our uploaded files, in this table I am creating following columns.
- DocumentID int primary key Identity yes
- DocumentName varchar(100) name of the document with extension
- Document varbinary(MAX) binary column for saving file in Binary format.
Open SQL Server Management Studio and open Northwind database and run following script for creating Table
Now we are ready with our Database creation so lets create a web application
Open Visual Studio and create a Web Application and in Default.aspx add following controls.
- One upload control
- One Button for uploading
- One DropDownList for displaying List of files which are in database already
- One Button for opening selected document.
Please refer following screen shot for design.
In Page_Load event we have to retrieve all documents which are already stored in database before so I have written a method called FillDropDown to fill the DropDownList
Once user selected a file to upload and click on Upload button we have to store that file in database in Binary format so I am using InputStream of uploaded file and reading into byte array and connection to database and storing the data.
Once user selects one uploaded file click on open I am retrieving the binary data of that file from database and using FileStream object I am saving the a folder, I am created a Folder called Documents in the solution itself and storing files in that folder, if a file already present in the folder it will be over written. please add following code in open button click event.
Now we are ready with our code just build, run and test.
Tags : Storing files into database, ASP.NET, C#, Web Application, FileStream, InputStream.
Hi,
ReplyDeleteThis is good,but i want to save image and retrieving the image from the SQLSERVER DATABASE
.I want same explanation step by step
Thanks for your response, I have already written an article about storing images in Database at following locaton
ReplyDeletehttp://satishjdotnet.blogspot.com/2009/04/save-images-in-access-database-aspnet.html
it is using Access Database however it is almost same for SQL Server.
regards,
satish.
Dear Sathis,
ReplyDeleteI have seen you in some web portal, you are doing great. and i would like to new .NET Programming web portal www.codegain.com it's successfully running with lost of articles and code snippets.
Even there 3 MVP and 5 Microsoft also joned in codegain.com. You are right creat article and support.
Since i would like to invite to codegain.com. this is my gmail id you can reach me vrrave@gamil.com
Thank you
RRaveen