Storing and calling Word files in the ASP.net program

Source: Internet
Author: User
Tags continue current time datetime file upload final flush how to use sql
asp.net|word| Program

This article provides an overview of how to use SQL Server2000 to store and invoke Word files in asp.net programs (without VBA).

(1) Establishing a database

First, we set up a table in the database with three fields, filename (varchar,50), Posttime (datetime,8), Filecontent (image,16), and store the file names separately. Upload time and the specific contents of the Word file, where the filename is the primary key. The specific SQL script is as follows:

CREATE TABLE [dbo]. [Word] (

[FileName] [varchar] (m) COLLATE chinese_prc_ci_as not NULL,

[Posttime] [DateTime] Not NULL,

[Filecontent] [Image] Not NULL

) on [PRIMARY] textimage_on [PRIMARY]


(2) Uploading and storing Word files

Create a asp.net Web application in Vs.net and add the following controls to the interface

control type

Id

Text

Description

Label

Label1

Please enter a title for the document

Label

Label2

Please select a specific document

File Field

File1

Upload Control (to convert this HTML control to a server control)

Textbox

Name_textbox

Used to enter the document title

Button

Btn_ok

Uploading files

Button

Btn_get

Reading files

HyperLink

HyperLink1

Open it

To open a Word document

Upload the file first through the upload control to find the required file upload, and then get the size of the file, and finally the flow of the form to write to the database, the specific code is:

private void Btn_ok_click (object sender, System.EventArgs e)
         {
string Name=name_textbox.text;
//Receive uploaded files
Stream Filestream=file1.postedfile.inputstream;
Gets the size of the uploaded file byte
int length=file1.postedfile.contentlength;
byte[] Worddata=new byte[length];
//Read bytes from stream and write to Worddata
int N=filestream.read (worddata,0,length);
//Get the current time
DateTime Time=datetime.now;
//Connection database
SqlConnection conn=new SqlConnection ();
Conn. connectionstring= "Workstation Id=tianchunzhu;packet size=4096;integrated security=sspi;data Source=TIANCHUNZHU; Persist security info=false;initial Catalog=test ";
SqlCommand cmd=new SqlCommand ();
cmd. Connection=conn;
cmd.commandtext= "INSERT into Word (filename,posttime,filecontent) VALUES (@fileName, @postTime, @fileContent)";
SqlParameter nameparam=new SqlParameter ("@fileName", system.data.sqldbtype.varchar,50);
Nameparam.value=name;
cmd. Parameters.Add (Nameparam);
SqlParameter timeparam=new SqlParameter ("@postTime", system.data.sqldbtype.datetime,8);
Timeparam.value=time;
cmd. Parameters.Add (Timeparam);
//Add Word File
SqlParameter contentparam=new SqlParameter ("@fileContent", System.Data.SqlDbType.Image); ①//See the final note of this paragraph
Contentparam.value=worddata;
cmd. Parameters.Add (Contentparam);
Conn. Open ();
cmd. ExecuteNonQuery ();
Conn. Close ();
         }

Note ① : Here because it is an image type file, you may not be able to predict the size of the file beforehand, so you do not have to specify the size parameter. If you want to control the size of the upload file, you can enter a size parameter. If you specify 1000, you can upload a 1k Word document when uploading.



(3) Read the data from the database and revert to the Word file

Reads data from the database into the buffer before writing the final file from the buffer. So first you have to open a buffer and set its size, and every time the buffer is read, write the data in the buffer into the file to empty the buffer and continue to read the data to the buffer until the last time that the remaining data in the buffer is written to the file, the new word document can be generated.

Because this section uses the input and output operations of the byte stream, you are referencing the System.IO namespace

Here is the complete code for this section:

private void Btn_get_click (object sender, System.EventArgs e)

{

//Connection database
SqlConnection conn=new SqlConnection ();
Conn. connectionstring= "Workstation Id=tianchunzhu;packet size=4096;integrated security=sspi;data Source=TIANCHUNZHU; Persist security info=false;initial Catalog=test ";
SqlCommand cmd=new SqlCommand ();
cmd. Connection=conn;
//Lookup reading based on the filename specified in the textbox
cmd.commandtext= "Select Filecontent from Word where filename= '" +name_textbox.text.tostring () + "'";
FileStream FS;
BinaryWriter bw;
//sets the maximum length allowed to read to the buffer
int buffersize=100;
//buffer to be read by byte stream
byte[] Outbyte=new byte[buffersize];
//Used to record the number of bytes that have been read
Long Reval;
//The index in the field from which to start the read operation
long StartIndex;
The relative or absolute path of the file to be encapsulated by the//filestream object
string filepath=@ "C:\wordData.doc";
Conn. Open ();
SqlDataReader Reader;
Reader=cmd. ExecuteReader ();
While (reader. Read ())
              {
fs=new FileStream (filepath,filemode.openorcreate,fileaccess.write);
bw=new BinaryWriter (FS);
startindex=0;
Reads a byte stream into the Outbyte buffer and returns the number of bytes read
Reval=reader. GetBytes (0,startindex,outbyte,0,buffersize);
//To unload data in the buffer and write data to the file when the read byte stream reaches the maximum allowable length of the buffer
While (reval==buffersize)
                   {
Bw. Write (Outbyte);
bw. Flush ();
//Reset the start read position and Continue reading and writing data
startindex+=buffersize;
Reval=reader. GetBytes (0,startindex,outbyte,0,buffersize);
}
//write the last remaining data in the buffer to the file
bw. Write (outbyte,0, (int) reval-1);
bw. Flush ();
bw. Close ();
FS. Close ();
}
Reader. Close ();
Conn. Close ();
}
The Word document is regenerated according to the path and name specified in filepath. You can specify the name and path of the generated Word document in filepath, depending on the situation.


(4) Open Word document

When you open a Word document This part of the text does not find an effective way to open Word directly through the button buttons, but we can hyperlink the control by pointing the NavigateUrl property of the hyperlink control to the physical path of the Word document.



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.