How to Save PDF, Word and Excel Files Into The DataBase

Introduction

This article shows how to save document files like PDF and Word files into a database using the FileUpload control of ASP.NET.

To help explain this article, I will use the following procedure:

  1. Create a table in a database to store the document files and some other relevant data by which I can fetch the documents from the table.
  2. Create a website with a page that contains some control like "textbox", "FileUpload" and "Button" on the design part of that page (.aspx).
  3. Write the code in the ".cs" file of that page to save the document files in the database at the "button click" event.

The following is the details of the preceding procedure.

Step 1

Create a table named "Documents" that will store:

  • Identity column for Serial number
  • Name of the file
  • Display File name that you want to show
  • Extension of file
  • Content Type of file
  • File in binary format
  • Size of file
  • Date of file insertion 
  1. create table Documents  
  2. (  
  3. SNo int identity,  
  4. Name_File varchar(100),  
  5. DisplayName varchar(50),  
  6. Extension varchar(10),  
  7. ContentType varchar(200),  
  8. FileData varbinary(max),  
  9. FileSize bigint,  
  10. UploadDate datetime  
  11. )  

create table Documents

Step 2

i) Create a new empty website named "FilesToBinary".

Create a new empty Website

ii) Add a new page named "Conversion.aspx".

Add a new Page

Step 3

Add 3 the following controls to the page:

  1. TextBox (to display the name of the file)
  2. FileUpload (for selecting the file)
  3. Button with Onclick event (for submitting the image)

Display Name

  1.         <asp:TextBox ID="txtfilename" runat="server">  
  2.         </asp:TextBox>  
  3. <br />  
  4.   
  5. Select File  
  6. <asp:FileUpload ID="FileUpload1" runat="server" />  
  7. <br />  
  8.   
  9. <asp:Button ID="Button1" runat="server"  
  10.     Text="Convert" OnClick="Button1_Click" />  
Write the code to insert the file into the database on the click event of the button.
  1.     protected void Button1_Click(object sender, EventArgs e)  
  2.     {  
  3.         if (!FileUpload1.HasFile)  
  4.         {  
  5.             Response.Write("No file Selected"); return;  
  6.         }  
  7.         else  
  8.         {            
  9.             string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);  
  10.             string extension = Path.GetExtension(filename);  
  11.             string contentType = FileUpload1.PostedFile.ContentType;  
  12.             HttpPostedFile file = FileUpload1.PostedFile;  
  13.             byte[] document = new byte[file.ContentLength];  
  14.             file.InputStream.Read(document, 0, file.ContentLength);  
  15.   
  16.             //Validations  
  17. if ((extension == ".pdf") || (extension == ".doc") || (extension == ".docx") || (extension == ".xls"))//extension  
  18.             {  
  19.                 if (file.ContentLength <= 31457280)//size  
  20.                 {  
  21.                     //Insert the Data in the Table  
  22.                     using (SqlConnection connection = new SqlConnection())  
  23.                     {  
  24. connection.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ToString();  
  25.                         connection.Open();  
  26.                         SqlCommand cmd = new SqlCommand();  
  27.                         cmd.Connection = connection;  
  28.                         string commandText = @"insert into Documents(Name_File,DisplayName,Extension,ContentType,FileData,FileSize,UploadDate)                                                   values(@Name_File,@DisplayName,@Extension,@ContentType,@FileData,@FileSize,getdate())";  
  29.                         cmd.CommandText = commandText;  
  30.                         cmd.CommandType = CommandType.Text;  
  31.                         cmd.Parameters.Add("@Name_File", SqlDbType.VarChar);  
  32.                         cmd.Parameters["@Name_File"].Value = filename;  
  33.                         cmd.Parameters.Add("@DisplayName", SqlDbType.VarChar);  
  34.   
  35.                         cmd.Parameters["@DisplayName"].Value = txtfilename.Text.Trim();  
  36.                         cmd.Parameters.Add("@Extension", SqlDbType.VarChar);  
  37.                         cmd.Parameters["@Extension"].Value = extension;  
  38.   
  39.                         cmd.Parameters.Add("@ContentType", SqlDbType.VarChar);  
  40.                         cmd.Parameters["@ContentType"].Value = contentType;  
  41.   
  42.                         cmd.Parameters.Add("@FileData", SqlDbType.VarBinary);  
  43.                         cmd.Parameters["@FileData"].Value = document;  
  44.   
  45.                         cmd.Parameters.Add("@FileSize", SqlDbType.BigInt);  
  46.                         cmd.Parameters["@FileSize"].Value = document.Length;  
  47.                         cmd.ExecuteNonQuery();  
  48.                         cmd.Dispose();  
  49.                         connection.Close();  
  50.                         Response.Write("Data has been Added");  
  51.                     }  
  52.   
  53.                 }  
  54.                 else  
  55.                 { Response.Write("Inavlid File size"); return; }  
  56.             }  
  57.             else  
  58.             {  
  59.                 Response.Write("Inavlid File"); return;  
  60.             }  
  61.         }  
  62.     }  
Note: You can also add some other validations like:
  • Check the length of file on client side.
  • Check the MIME type of the file on server side.
Step 4

 Run the page; it will be like:


Run the Page

Now I will upload 3 files of various types like Word, PDF and Excel files one by one using the following procedure:

  1. Fill in the Display name and click on the browse button to select the file.

    upload files

  2. After selecting the file.

    After selecting the file

  3. Click on the convert button to save the file.

    covert button

Then do the same procedure for PDF and Excel files.

Result

Now you can see all the files were saved in the database in binary format.

saved in the database