Asp.net solution for uploading files to the database, asp.net for uploading files

Source: Internet
Author: User

Asp.net solution for uploading files to the database, asp.net for uploading files

Now, let's look at the database table structure for storing files. Here, we provide the standard SQL statement for creating a 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 preceding statement, we can see that the data table tblBooksUpload contains five fields:

· The DocID field is the table's key field and the data record number;

· The DocTitle field is used to briefly describe how to upload a file. If you upload a text file, we generally set it as the file title, image, program, and so on, and a brief introduction of the image and program;

· The Field Doc is used to store the fields of the uploaded files. Note that the Doc field is set to the Image category here;

· The DocType field is used to save the type of the uploaded file. Maybe we wonder why this field is required? In fact, this field is very important. When you obtain data from the database, this field will be used to specify the data category in the data field Doc. Then, the browser determines the data presented to the user based on this field;

· The DateTime field is a time field. We can see that the value of this field is taken from the current date of the server.

The following is the stored procedure of data insertion. Let's look at the specific code:

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

Now, let's take a look at the specific steps for uploading files to the database from the text, and then proceed with the code:
First, obtain the uploaded file from the client, and then put it into the data stream;
Second, the server reads the data stream and saves it to the cache;
Third, save the cached data to the database;

Now, let's take a step-by-step look at how to implement these functions in the program.
Step 1
Of course, first, we need to enable users to freely select files on the browser side and then upload files. Here, the user selects files. Of course, the standard Windows mode is required. Therefore, here we use the Form File component to select a File. Note: because the file is uploaded, we should set the Form attribute to multipart/form-data so that the file can be uploaded correctly. The main code for uploading a page is as follows:

<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 files to the cache through data streams. The cache size is the same as the file size. We can use the following code to obtain the file size:

int intDocLen = txtFileContents.PostedFile.ContentLength;

Then, we can set the specific cache size:

byte[] Docbuffer = new byte[intDoclen];

After this setting, we can save the content 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 from the cache position 0 until the length of the entire file. In fact, this is the size of the entire file or the entire cache.

Step 3

Now, we need to save the cached data to the database until the data table structure. In this way, we can implement this function by writing simple SQL statements. In the above content, we have written a stored procedure. In the program, we only need to create a SqlCommand object and pass the stored procedure to it, set the "@ Doc" parameter to retrieve 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 is used to save the type of the uploaded file string strDocType; // used to save the file size int intDocLen; // Stream is used to read the 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 file content 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 ();}}}

Summary
The method we mentioned above is suitable for all types of files. By modifying the code above, we can build a file management system fully based on databases.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.