asp. net Upload File to Database Solution

  • 2021-07-02 23:52:07
  • OfStack

Now, let's look at the database table structure where the files are stored. Here, we give the standard SQL statement for creating the table:


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

In the above statement, we see that the data table tblBooksUpload contains five fields:

The field DocID is the key field of the table and the data record number;

The field DocTitle is used to simply explain the uploaded file. If the text file is uploaded, we will set it as the file title, image, program, etc., and set it as a brief introduction of the image and program;

The field Doc is used to store the files we upload. Note that the Doc field is set to Image category here;

The field DocType is used to save the type of file we uploaded. Maybe we wonder why we want this field. In fact, this field is very important. When the user obtains data from the database, this field will be used to specify the category of data in the data field Doc, and then the browser will decide the data presented to the user according to this field;

The field DateTime is a time field, and we can see that the value of this field is taken from the current date of the server.

The following is a stored procedure for inserting data. Let's look at the specific code:


CREATE PROCEDURE uSP_BooksUploadFile
@Title varchar(200),
@Doc image,
@DocType varchar(4)

AS

INSERT tblBooksUpload(DocTitle,Doc,DocType)
VALUES (@Title,@Doc,@DocType)

GO

Now, we first understand the specific steps of uploading files to the database from the text, and then realize it from the code:
First, we get the uploaded file from the client, and then we put it into the data stream.
Second, the server reads the data stream and then saves it to the cache;
Third, saving the cached data to the database;

Now, let's look at how to implement these functions in the program step by step.
Step 1
Of course, first of all, we need to realize the user's free selection of files on the browser side, and then upload them. Here, the user selects files, which of course requires the standard Windows mode. Therefore, we use the File file component of Form to select files for the user here. Note that because the file is uploaded, when setting the attribute of Form, we should set it to multipart/form-data, so that the file can be uploaded correctly. The following is the main code for uploading the page:


 < 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 > 

Step 2

We can save the uploaded file to the cache through data stream. The cache size is the same as the specific size of the file. We can use the following code to get the specific size of the file:


int intDocLen = txtFileContents.PostedFile.ContentLength;

Then, we can set the specific size of the cache:


byte[] Docbuffer = new byte[intDoclen];

After this setting, we can save the contents of the uploaded file to the cache:


Stream objStream;
objStream = txtFileContents.PostedFile.InputStream;
objStream.Read(Docbuffer,0,intDocLen);

In the above code, when reading the cache, it starts at the 0 position of the cache and reaches the length of the whole file, which is actually the size of the whole file or the whole cache.

Step 3

Now all we need to do is save the cached data to the database, and we have reached the data table structure, so we can do this by writing a simple SQL statement. In the above content, we wrote a stored procedure. In the program, we only need to create an SqlCommand object and pass this stored procedure to it, and set the "@ Doc" parameter to get the cached data:


cmdUploadDoc = new 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;

Click the button to process the code


private void btnSubmit_Click(object sender, System.EventArgs e)
{
   string strDocExt;
   //strDocType The type used to save the uploaded file 
   string strDocType;

   // Used to save file size 

   int intDocLen;

   //Stream Used to read uploaded data 

   Stream objStream;
   SqlConnection BooksConn; 
   SqlCommand cmdUploadDoc;

   if(IsValid)
   {
        if(txtFileContents.PostedFile != null)
        {
             // File type 
             strDocExt = CString.Right(txtFileContents.PostedFile.FileName,4).ToLower();
             switch(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;
             }
             // Upload the specific contents of the file 
             intDocLen = txtFileContents.PostedFile.ContentLength;
             byte[] Docbuffer = new byte[intDocLen];
             objStream = txtFileContents.PostedFile.InputStream;

             // Save the file to the cache  
             // The cache will be saved to the database 

             objStream.Read(Docbuffer ,0,intDocLen);
             BooksConn = new SqlConnection("Server=Server;UID=sa;Database=Books");
             cmdUploadDoc = new 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();
        }
   }
}

Summarize
The method mentioned above is suitable for all types of files. If the above code is modified appropriately, we can establish a file management system based entirely on database.


Related articles: