ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Save and Retrieve Files from SQL Server Database using ASP.Net
Author Name: Mudassar Khan Published Date: February 19, 2009
Filed Under :
ASP.Net
 |
C#.Net
 |
VB.Net
 |
SQL Server
Views: 35724

Files can be easily saved in the SQL Server Database Saving it in database makes it easily manageable.

Here I will explain how to save and retrieve files from database.


Database Design


Here I have created a Database called dbFiles and it has a table called tblFiles.

It has 4 Fields. The complete description is available in the Figure below




As you can see above for the id field I have set Identity Specification true, so that it automatically increments itself.


Field

Relevance

id

Identification Number

Name

File Name

Content Type

Content Type for the file

Data

File stored as Binary Data


Content Type

Depending on the type of the file below are the content types


File Type

Content Type

Word Document

application/vnd.ms-word

Excel Document

application/vnd.ms-excel

JPEG Image

image/jpeg

Portable Document Format

application/pdf


In the source code attached I have added the database files. You will need to attach it to your SQL Server.


Connection String

Below is the connection string to the database. You can modify it to suit yours


<connectionStrings>

<add name="conString" connectionString="Data Source=.\SQLEXPRESS;database=dbFiles; Integrated Security=true"/>

</connectionStrings >

 


Reading the File

The files will be read into a File Stream and then the File Stream will be converted into byte array using BinaryReader in order to save into the database table.


C#


// Read the file and convert it to Byte Array

string filePath = Server.MapPath("APP_DATA/TestDoc.docx");

string filename = Path.GetFileName(filePath);

 

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

BinaryReader br = new BinaryReader(fs);

Byte[] bytes = br.ReadBytes((Int32)fs.Length);

br.Close();

fs.Close();



VB.Net


' Read the file and convert it to Byte Array

Dim filePath As String = Server.MapPath("APP_DATA/Testxls.xlsx")

Dim filename As String = Path.GetFileName(filePath)

 

Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)

Dim br As BinaryReader = New BinaryReader(fs)

Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))

br.Close()

fs.Close()

 


Saving the File to Database

 

Once the File is converted into Byte Array it will be inserted into the database. The File Name, File Content Type and the Binary data which resembles the file are stored in the database.

 

The figure below shows the data being stored in the table.




C#

//insert the file into database

string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";

SqlCommand cmd = new SqlCommand(strQuery);

cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;

cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";

cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;

InsertUpdateData(cmd);

 


VB.Net

'insert the file into database

Dim strQuery As String = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)"

Dim cmd As SqlCommand = New SqlCommand(strQuery)

cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename

cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-excel"

cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes

InsertUpdateData(cmd)



And the function InsertUpdateData accepts the SqlCommand object, executes the query and inserts the data into the database.


C#

private Boolean InsertUpdateData(SqlCommand cmd)

{

    String strConnString = System.Configuration.ConfigurationManager

    .ConnectionStrings["conString"].ConnectionString;

    SqlConnection con = new SqlConnection(strConnString);

    cmd.CommandType = CommandType.Text;

    cmd.Connection = con;

    try

    {

        con.Open();

        cmd.ExecuteNonQuery();

        return true;

    }

    catch (Exception ex)

    {

        Response.Write(ex.Message);

        return false;

    }

    finally

    {

        con.Close();

        con.Dispose();

    }

}

 


VB.Net

Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean

    Dim strConnString As String = System.Configuration.

    ConfigurationManager.ConnectionStrings("conString").ConnectionString

    Dim con As New SqlConnection(strConnString)

    cmd.CommandType = CommandType.Text

    cmd.Connection = con

    Try

      con.Open()

      cmd.ExecuteNonQuery()

      Return True

    Catch ex As Exception

      Response.Write(ex.Message)

      Return False

    Finally

      con.Close()

      con.Dispose()

    End Try

End Function

 

For more details on how to Execute Parameterized queries refer Using Parameterized queries to prevent SQL Injection Attacks in SQL Server.


Retrieving the File from Database

 

To retrieve the file from the database, a select query is executed and the ID of the file is passed as the parameter.

The command object is prepared and is passed to the GetData which returns the DataTable which contains the desired file data.

Then the DataTable is passed to the download function which starts the download of the file.

 

C#

string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";

SqlCommand cmd = new SqlCommand(strQuery);

cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;

DataTable dt = GetData(cmd);

if (dt != null)

{

    download(dt);

}



VB.Net


  Dim strQuery As String = "select Name, ContentType, Data from tblFiles where id=@id"

  Dim cmd As SqlCommand = New SqlCommand(strQuery)

  cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1

  Dim dt As DataTable = GetData(cmd)

  If dt IsNot Nothing Then

       download(dt)

  End If


Below is the code for the GetData function. It is a simple function that executes the Select query.

More details on the function you can refer here.


C#


private DataTable GetData(SqlCommand cmd)

{

    DataTable dt = new DataTable();

    String strConnString = System.Configuration.ConfigurationManager

    .ConnectionStrings["conString"].ConnectionString;

    SqlConnection con = new SqlConnection(strConnString);

    SqlDataAdapter sda = new SqlDataAdapter();

    cmd.CommandType = CommandType.Text;

    cmd.Connection = con;

    try

    {

        con.Open();

        sda.SelectCommand = cmd;

        sda.Fill(dt);

        return dt;

    }

    catch

    {

        return null;

    }

    finally

    {

        con.Close();

        sda.Dispose();

        con.Dispose();

    }

}



VB.Net


Public Function GetData(ByVal cmd As SqlCommand) As DataTable

   Dim dt As New DataTable

   Dim strConnString As String = System.Configuration

   .ConfigurationManager.ConnectionStrings("conString").ConnectionString()

   Dim con As New SqlConnection(strConnString)

   Dim sda As New SqlDataAdapter

   cmd.CommandType = CommandType.Text

   cmd.Connection = con

   Try

      con.Open()

      sda.SelectCommand = cmd

      sda.Fill(dt)

      Return dt

   Catch ex As Exception

      Response.Write(ex.Message)

      Return Nothing

   Finally

      con.Close()

      sda.Dispose()

      con.Dispose()

   End Try

End Function


Download the File


Here is the function which initiates the download of file. It basically reads the file contents into a Byte array and also gets the file name and the Content Type. Then it writes the bytes to the response using Response.BinaryWrite


C#


private void download (DataTable dt)

{

    Byte[] bytes = (Byte[])dt.Rows[0]["Data"];

    Response.Buffer = true;

    Response.Charset = "";

    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    Response.ContentType = dt.Rows[0]["ContentType"].ToString();

    Response.AddHeader("content-disposition", "attachment;filename="

    + dt.Rows[0]["Name"].ToString());

    Response.BinaryWrite(bytes);

    Response.Flush();

    Response.End();

}


VB.Net


Protected Sub download(ByVal dt As DataTable)

  Dim bytes() As Byte = CType(dt.Rows(0)("Data"), Byte())

  Response.Buffer = True

  Response.Charset = ""

  Response.Cache.SetCacheability(HttpCacheability.NoCache)

  Response.ContentType = dt.Rows(0)("ContentType").ToString()

  Response.AddHeader("content-disposition", "attachment;filename="

  & dt.Rows(0)("Name").ToString())

  Response.BinaryWrite(bytes)

  Response.Flush()

  Response.End()

End Sub



Here I have described only for a word file similarly you can save Excel, Image and PDF. In the source code I have done the same for Excel, Image and PDF files too.

You can download the complete Source code here.

SaveRetrieveFiles.zip (1.67 mb)


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

Nikhil said:
I tried above code.But after downloading it ask to open or save.br In case of open optionit cant open in proper format or show corrupted file.br Reply
January 08, 2010  

Mudassar Khan said:
Reply To: Nikhil
Check whether file is stored in database or not
January 08, 2010  

Shaili said:
Hibr Very nice article. br I am trying to use it in my application to open a .pdf file. Everything seems to work fine for word and excel documents. I get an error (not in .net though) when the adobe pdf application opens. Following is the error: There was an error opening this document. This file cannot be found. The file exists in AppData folder just as in your example. Would you have any idea what may be causing this I can open the file by itself but not through the application. br Please advice.br Thanks
January 13, 2010  

Mudassar Khan said:
Reply To: Shaili
That's a strange error I never faced such anytime. Create another folder called files and try to place the documents there instead of APP_DATA
January 13, 2010  

adil said:
Hibr I used download function br Response.Buffer Truebr Response.Charset br Response.Cache.SetCacheability(HttpCacheability.NoCache)br Response.ContentType applicationvnd.ms-wordbr Response.AddHeader(content-disposition attachmentfilename filename)br Response.BinaryWrite(bytes)br Response.Flush()br Response.End()br br but word doc is corrupted when opened in ms-word client and also in firefox i am facing problems
January 23, 2010  

Mudassar Khan said:
Reply To: adil
Hi Adil,
Have you tried the sample since such issue was never faced by anyone.

This can only happen when there's issue while saving the file in database and it might got corrupted
and another might be when you are downloading a non word file as word document
January 24, 2010  

Lalita Mishra said:
I tried code written above but got exception message-String or binary data would be truncated. The statement has been terminatedbr I set in my sql-2000 datatype of Data as Varbinary(50) and remaining code are same.Please give reply.Thanks in advancebr
February 14, 2010  

Mudassar Khan said:
Reply To: Lalita Mishra
Set it to varbinary(8000)
February 15, 2010  

main said:
hi if i store the file in DB br br i want to open the pdf file directly on web page itself it should ask open Save dialog box. how
February 15, 2010  

Mudassar Khan said:
Reply To: main
Comment the line that says

Response.AddHeader....
February 15, 2010  

mani said:
When i remove or Comment the Response.AddHeader it show the page like this br br The XML page cannot be displayed br Cannot view XML input using style sheet. Please correct the error and then click the Refresh button or try again later. br br br --------------------------------------------------------------------------------br br An invalid character was found in text content. Error processing resource http:localhost:1923siteNameSubMenuFile.aspxf...br br br
February 15, 2010  

Mudassar Khan said:
Reply To: mani
This application has not been tested with XML Files. If you need display xml files use proper content type
February 16, 2010  

mani said:
hi its not working ie: getting pdf file from DB and show on the web page itself..
February 16, 2010  

Mudassar Khan said:
Reply To: mani
That's the error from your browser and it can be because it can't display PDF or PDF Viewer is not installed.
February 16, 2010  

mani said:
if I remove the br br Response.AddHeader br br in IE 6 when i click the download PDF file - it shows this errorbr br An invalid character was found in text content. Error processing resource http:localhost:2469IQMathsSubMenuFile.ashxf...br br The same has been run it on Mozilla 3.6 it show the openSave dialog box for the FileHandler.ashx file. br br you said the PDF viewer have to instal on the browser br br there is no sure that the user should have PDF viewer .br br Could u tell any other better option..
February 16, 2010  

Mudassar Khan said:
Reply To: mani
Yes if there is no PDF viewer there is no option other then simply letting the user download.
February 16, 2010  

kent said:
it is not working with me i cant download the files i follow the instruction above still nothing happens i get binary data in the Data column what should i do need help please
February 25, 2010  

Mudassar Khan said:
Reply To: kent
Yes in database it is stored as binary data. Have you tried the Sample attached?
February 25, 2010  

kent said:
no i mean binary data and when i try to download it no pop-up appear and i dont know what happen i follow the command correctly
February 25, 2010  

Mudassar Khan said:
Reply To: kent
It is difficult to predict what you did wrong in your code. My guess is Content type is improper. Please post your question along with code on forums.asp.net I am member there
February 26, 2010  

Donald Willis said:
Thanks for the helpful tutorial. I seem to be able to upload the files to my server when I run the site on a local computer but once I publish the site to the server the upload functionality doesnt go through I dont even get an error message.br br Any advice
March 02, 2010  

Mudassar Khan said:
Reply To: Donald Willis
Generally on server. you need to provide appropriate permissions
March 02, 2010  

Faisal Habib said:
How can we use this approach to save and retrieve ZIP files What will be the content type
March 03, 2010  

Mudassar Khan said:
Reply To: Faisal Habib
Use this
application/x-zip-compressed
March 04, 2010  

Faisal Habib said:
Thanks a lot for nice article and response.. br br I want to ask how we can store file in file system directly retrieving content from DB instead of having save dialogue box. Please reply its urgent
March 07, 2010  

Mudassar Khan said:
Reply To: Faisal Habib
That's not possible as you cannot access the client's machine due to security reasons
March 08, 2010  

Akanksha said:
gr8.br usefull. its really stepwise and systematicbr I followed successfully...br but its showing error at br br return truefalsebr saying InsertUpdate data returing voidvoid keyword must not be followed by object expression...br pls help
March 16, 2010  

Mudassar Khan said:
Reply To: Akanksha
Try to download and verify with the sample
March 16, 2010  

Abhisek Panda said:
Hi Your article helped me a lot. But while trying to update the image in the table it is not updated. Sometime it is being updating and some time not. Is there any timing constraint to update the varbinary databr br Other tables are updating frequently but the problem is withe the table with varbinary data.
April 11, 2010  

Mudassar Khan said:
Reply To: Abhisek Panda
No, I don't think there is any such constraint the update should work fine. check what size you have set for the binary field make it to maximum
April 11, 2010  

Sanrosh said:
Hi thanks a lot for this post i have one question i am saving file in database as binary data . I want to fetch the file from database and bind it to the gridview to download . Contenttype is necessary since i am not storing content type of the file . Please do reply
April 15, 2010  

Mudassar Khan said:
Reply To: Sanrosh
Yes if you provide content type it is easy for browser to understand what type of file is being downloaded and it also avoids the risk of file getting corrupted
April 17, 2010  

slemza said:
Hi what a useful article. Can you provide some elaboration on how this can be displayed on a gridview after uploading. and i seem not to understand where the original files get saved after hiting button upload. pls reply
April 20, 2010  

Khoo said:
Hi. Thanks for you nice article. Please tell me how to display any of file types directly on aspx webpage instead of display saving box...br br Sorry for my bad English. Thank you.
April 20, 2010  

Mudassar Khan said:
Reply To: slemza
You will have to fire a select query and then bind th results to grid
April 22, 2010  

Mudassar Khan said:
Reply To: Khoo
All files cannot be displayed. also they will be displayed only if the software is present and remove this line

Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
April 22, 2010  

Acoustic said:
Hello this has been the best of all the demos Ive seen...and Ive probably gone through 40 without dicovering one that was this well explained.br br Howeverwhen I load my page it briefly shows the first picture and then has this error:br br There is no row at position 0.br br What can I do to make it go away...what am I missing
May 25, 2010  

Mudassar Khan said:
Reply To: Acoustic
make sure you add null checks before accessing the data
May 25, 2010  

Acoustic said:
First off thanks for the article...its a godsent after having had tried other solutions and failed for two days. About checking nulls I only have two images in my table and neither rows has a null unless this is considered a null: Binary data in my image column. Both images actually do show up and then shortly thereafter theres the There is no row at position 0 exception thrown. Anyhow how do I check nulls to avoid this exceptionbr
May 25, 2010  

Mudassar Khan said:
Reply To: Acoustic
You will need to check this way

if(dt.Rows[0] != null)
{
//Place code here
}

Do this in download method
May 25, 2010  

Acoustic said:
Great Favourited your site because your instructions are so clearbr br Thank you.
May 25, 2010  

pauline said:
Heybr br How can I save files from database SQL server using Fileupload control in asp.net And how do i retrieve it thanks
June 06, 2010  

Mudassar Khan said:
Reply To: pauline
Refer here
http://www.aspsnippets.com/Articles/Save-and-Retrieve-Files-from-SQL-Server-Database-using-ASP.Net.aspx

http://www.aspsnippets.com/Articles/Save-Files-to-SQL-Server-Database-using-FileUpload-Control.aspx
June 07, 2010  

Mistry Hardik said:
you are a saviour thank you for such a clean development.br br Regardsbr Hardik
June 25, 2010  

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code