Upload Document to The Database PDF Print E-mail
User Rating: / 0
PoorBest 
Monday, 09 March 2009
HTML clipboard

Introduction:

In this tutorial We will see how we can upload a document & then store its content in a database. Here I am just focus on uploading Text based Documents not images or sound etc..

Why did I do this?!

Becasue I am planning to build another Tutroial which will use Full Text Search Functionality in SQL Server Database, I'll use it to search the uploaded Document.

Note:

It will also allow you to store Images and sounds format in a database.

Create a Database Table

This will be the table which will hold the Document information.

CREATE TABLE tblBooksUpload
(
    DocID int NOT NULL IDENTITY Primary Key ,
    DocTitle varchar (200) ,
    Doc image,
    DocType varchar (50) ,
    Entrydate datetime  Default GetDate()
)

DocType Column will hold the document type: doc, ppt, htm, or tex, etc...

Doc Column will hold the document content.

Now here is the insert STORED PROCEDURE:

CREATE PROCEDURE uSP_BooksUploadFile
@Title varchar(200),
@Doc image,
@DocType varchar(4)
AS
INSERT tblBooksUpload(DocTitle,Doc,DocType)
VALUES (@Title,@Doc,@DocType)
GO

Steps for uploading documnet

1-After Accept the uploaded file with HtmlInputFile we put it in an Stream

2-Read That Stream And store it into a Buffer

3-Send the buffer to the database to store it.

We will see how to implement those three steps now.

First Step

we will need an upload field in the aspx page, and do not forget to add the attribute enctype="multipart/form-data" to your Form.

Form Code:

<form id="frmUpload" method="post" enctype="multipart/form-data" runat="server">
    <span>Title</span><br>
    <asp:textbox id="txtTitle" runat="server" EnableViewState="False"></asp:textbox>
    <asp:requiredfieldvalidator id="valrTitle" runat="server" ErrorMessage="*
Required" ControlToValidate="txtTitle">* Required</asp:requiredfieldvalidator>
    <br>
    <br>
    <span>Docutment to Upload</span><br>
    <input id="txtFileContents" type="file" runat="server" NAME="txtFileContents">
    <br>
    <br>
    <asp:button id="btnSubmit" Text="Submit" Runat="server"></asp:button>
</form>

Second Step

We Will Store the content of the document in a buffer using a Stream, Size of buffer is the same as the document size-Lenght- which we can determine this way:

//PostedFile Property of Type HTTPPostedFileint intDocLen = txtFileContents.PostedFile.ContentLength;

Then we can set Buffer Size, Note that the buffer is a byte buffer:

byte[] Docbuffer = new byte[intDoclen];

After that we will store the content of the uploaded file in the buffer:

Stream objStream;
//InputStream://Gets a Stream object which points to an uploaded Document; 
//to prepare for reading the contents of the file.
objStream = txtFileContents.PostedFile.InputStream;
objStream.Read(Docbuffer,0,intDocLen);

Read Method Accepts 3 arguments, The buffer, offset, Count, here offest is (0) means we read from the beginnig of the stream, and the count set to be the document length, which mean we keep read till the end of the stream,, this is all mean we read the whole stream.

Third & Last Step

All we need now is to store the buffer in the Database, and it is very easy as long as you have the database table and you know some SQL Statments. We built our Procedure which will perform the insert operation, all I'll do now is to send this Procedure to the SqlCommand Object and set the Value of the "@Doc" Parameter to hold buffer:

//BooksConn is the connection objectnew SqlCommand("uSP_BooksUploadFile",BooksConn);
cmdUploadDoc.CommandType = CommandType.StoredProcedure;
//Add the Params which in the Stored Proc //Set Params Values
//Set the "@Doc" Param to be Docbuffer byet Array
cmdUploadDoc = 
cmdUploadDoc.Parameters.Add("@Title ",SqlDbType.VarChar,200);
cmdUploadDoc.Parameters.Add("@Doc",SqlDbType.Image);
cmdUploadDoc.Parameters.Add("@DocType",SqlDbType.VarChar,4);
cmdUploadDoc.Parameters[0].Value = txtTitle.Text;
cmdUploadDoc.Parameters[1].Value = Docbuffer;
cmdUploadDoc.Parameters[2].Value = strDocType;

Code Behind:

This is the Handle Method of the btnSubmit Click Event:

private void btnSubmit_Click(object sender, System.EventArgs e)
{
string strDocExt;
//strDocType to store Document type which will be Stored in the Databasestring strDocType;
//Will be used to determine Document lengthint intDocLen;
//Stream object used for reading the contents of the Uploading Documnetif(IsValid)
{
if(txtFileContents.PostedFile != null)
{
//Determine File Typeswitch(strDocExt)
{
case ".doc":
strDocType = "doc";
break;
case ".ppt":
strDocType = "ppt";
break;
case ".htm":
strDocType = "htm";
break;
case ".html":
strDocType = "htm";
break;
case ".jpg":
strDocType = "jpg";
break;
case ".gif":
strDocType = "gif";
break;
default:
strDocType = "txt";
break;
}
//Grab the Content of the Uploaded Document
//buffer to hold Document Contentsnew byte[intDocLen];
//InputStream://Gets a Stream object which points to an uploaded Document; 
//to prepare for reading the contents of the file.//Store the Content of the Documnet in a buffer
//This buffer will be stored in the Database//Add Uploaded Documnet to Database as Binary
//You have to change the connection stringnew
 //Setting the SqlCommandnew //End of if(txtFileContents.PostedFile != null)//End Of if(IsValid)
//End of Method btnSubmit_Click
Stream objStream;
SqlConnection BooksConn;
SqlCommand cmdUploadDoc;
strDocExt = CString.Right
(txtFileContents.PostedFile.FileName,4).ToLower();
intDocLen = txtFileContents.PostedFile.ContentLength;
byte[] Docbuffer = 
objStream = txtFileContents.PostedFile.InputStream;
objStream.Read(Docbuffer ,0,intDocLen);
BooksConn = 
SqlConnection("Server=Server;UID=sa;Database=Books");
cmdUploadDoc = 
SqlCommand("uSP_BooksUploadFile",BooksConn);
cmdUploadDoc.CommandType = CommandType.StoredProcedure;
cmdUploadDoc.Parameters.Add("@Title ",SqlDbType.VarChar,200);
cmdUploadDoc.Parameters.Add("@Doc",SqlDbType.Image);
cmdUploadDoc.Parameters.Add("@DocType",SqlDbType.VarChar,4);
cmdUploadDoc.Parameters[0].Value = txtTitle.Text;
cmdUploadDoc.Parameters[1].Value = Docbuffer ;
cmdUploadDoc.Parameters[2].Value = strDocType;
BooksConn.Open();
cmdUploadDoc.ExecuteNonQuery();
BooksConn.Close();
}
}
}
Last Updated ( Monday, 09 March 2009 )
 
< Prev   Next >
School Joomla Templates and Joomla Tutorials