Use Delphi to develop File Upload components for ASP

Source: Internet
Author: User
Tags ole

 

Using Delphi to upload ASP development files

ASP (Active Server Page) is a product of Microsoft. It is easy to program and can quickly develop dynamic websites with powerful functions. Many websites (especially intranet/exclusive intranet) using the NT + IIS + ASP mode, ASP becomes a popular scripting language for website development. In Web Services, file upload is a common feature, while PWS in Win9x does not provide related components. IIS in NT provides a post acceptor component, however, it is not easy to use because it needs to check the user's WWW access permissions; it can also download the relevant components from the Internet, but most of these are commercial components, used to download a trial version, there are limits on the time or function used. Because ASP can call standard OLE/COM components, we can use advanced programming tools such as VB, Vc, and Delphi to customize our asp File Upload components according to our own requirements, meet your application system requirements.

The following describes how to use Delphi to develop the File Upload Component for ASP and how to implement it.

I. Implementation principle of File Upload

Data uploading Based on Web is subject to the rfc1867 standard, and the uploaded file data is no exception. For example, use the following HTML page file (delphiup.htm) and Select Upload file:

<! -- Delphiup.htm: file upload interface -->

<HTML>

Use the File Upload Component compiled by Delphi to upload files

<Form name = "uploadform" Action = "delphiup. asp" method = "Post" enctype = "multipart/form-Data">

<P> Save the file as: <input type = text name = "saveas">

<P> select the uploaded file: <input type = file name = "filedata">

<Input type = "Submit" name = "B1" value = "Confirm upload"> </P>

</Form>

</Body>

When the client selects a file (such as test. txt, its content is "here is the content of a file for upload .") And press

After the "Confirm upload" button submits data, the data received by the server program will take the following form:

----------------------------- 7cf1d6c47c #13 #10

Content-Disposition: Form-data; name = "saveas" #13 #10 #13 #10

Newfilename #13 #10

----------------------------- 7cf1d6c47c #13 #10

Content-Disposition: Form-data; name = "filedata"; filename = "D:/test.txt"

Content-Type: text/plain #13 #10 #13 #10

Here is the content of a file for upload. #13 #10

----------------------------- 7cf1d6c47c #13 #10

Content-Disposition: Form-data; name = "B1" #13 #10 #13 #10

Confirm upload #13 #10

----------------------------- 7cf1d6c47c --

Where, "----------------------------- 7cf1d6c47c" is the delimiter used to separate fields in the form;

#13 #10 is the Delphi representation of the carriage return line break. We can think that the Information Description of each form field starts with a carriage return line break #13 #10. The form domain name starts with "name =, end with "". The form field value starts with two carriage return linefeeds #13 #10 #13 #10 and ends with a line break #13 #10 # With a line break; the file name starts with "filename =" "and ends. With these marks, we can get the name and value of the form field and the name of the file to be uploaded, so as to read and store the file data.

II. Implementation of File Upload

After understanding the data format mentioned above, it is no longer difficult for us to compile a File Upload Component by ourselves.

(1) Create an ASP Component Project

If you are not familiar with the procedure of using Delphi to develop OLE Automation server, for more information, see "electronic and computer", an article entitled "using Delphi to develop OLE Automation server for ASP" in 06th.

Here is a brief introduction to the procedure.

1. Create an ActiveX Library Project

In Delphi, select "file =" new... "and select" ActiveX library "on the ActiveX tab of the" new item "dialog box. Delphi will automatically create a DLL project project1.

2. Create automation components

In Delphi, select file =, new ..., select "Automation Object" on the ActiveX tab of the "new item" dialog box, and enter the class name (such as "uploadfile") in the "Automation Object wizard" dialog box "), select "multiple instance" for instancing. After you click "OK", Delphi will automatically create a TLB (Type Library) file project1_tlb.pas and a PAS (unit) file unit1.pas. In the Type Library Design window, change project1 to myupload, And the OLE registration code of the File Upload Component is "myupload. uploadfile ".

3. Introduce ASP database

To use ASP's five built-in objects (request, response, server, application, and Session), you need to introduce the ASP library. We mainly use the request object to read data transmitted from the client to the server.

Select "Import Type Library" from the project menu, and select "Microsoft Active Server Pages Object Library (Version 2.0)" in the "type libraries" list in the "Import Type Library" dialog box) "(If this option is not available, make sure that iis3 or above or pws4 is installed on your computer and ASP. DLL has been correctly registered), Delphi will automatically create a TLB file asptypelibrary_tlb.pas, which contains the ASP object type declaration we need.

4. Define the onstartpage and onendpage Processes

When server. when Createobject creates an OLE object instance, the web server calls its onstartpage method to pass ASP application environment information to this object. In this process, we can obtain client information; when an OLE object instance is released on the ASP page, the web server will call its method onendpage. In this process, we can release the memory and perform other end operations. In our component, we need to use its onstartpage method.

The onstartpage method should be defined in unit1.pas. The function prototype of onstartpage is:

Procedure onstartpage (ascriptingcontext: iunknown );

The ascriptingcontext parameter is an iscriptingcontext type variable. It contains five attributes (request, response, server, application, and session) that correspond to the five built-in objects with the same name in ASP.

In The TLB definition window (view => Type Library), add the onstartpage Method for iuploadfile. The declaration statement is "procedure onstartpage (ascriptingcontext: iunknown );".

(2) extract data uploaded by the client

This can be done in the onstartpage process.

You can use the totalbytes (length of Request Information Content) attribute in the request (type: irequest) attribute of ascriptingcontext and the binaryread method to read the request information data uploaded by the client to a byte array, then, the data is analyzed and extracted according to the data format defined in rfc1867.

1. First, several private variables of tuploadfile are defined.

Add a reference (uses) to asptypelibrary_tlb.pas in the unit file up01.pas (saved by unit1.pas ),

Then join

Private

Fcontentlength: longint; // length of the Request Information

Fcontentdata: variant; // content data, which stores the request information in Arrays

Ffilename, // name of the file to be uploaded

Fdelimeter: string; // form field delimiter

Fscriptingcontext: iscriptingcontext; // ASP processes context content

Ffiledatastart, // file data start location

Ffiledataend: longint; // end position of the file data

2. Extract the request information data uploaded by the client

// In the onstartpage event, obtain ASP context information, request information content, form field delimiters, and file data.

Procedure tuploadfile. onstartpage (ascriptingcontext: iunknown );

VaR

Arequest: irequest; // www request object

Aolevariant: olevariant; // records the length of the request information.

Intdelimterlength: integer; // delimiter Length

Longindex, alongint, longpos: longint;

Contentdata: ansistring; // string representation of the Request Information Content

Strtemp: string;

Findendoffiledata: Boolean; // whether the end position of the file data is found

Begin

// Extract the request information data uploaded by the client

Fscriptingcontext: = ascriptingcontext as iscriptingcontext; // obtain ASP context information

Arequest: = fscriptingcontext. Request; // obtain WWW request information

Fcontentlength: = arequest. totalbytes; // length of the Request Information

// Create a dynamic array to store the request information in the form of an array

Fcontentdata: = vararraycreate ([0, fcontentlength], varbyte );

// Store the request information in the array

Aolevariant: = fcontentlength;

Fcontentdata: = arequest. binaryread (aolevariant); // read the request information

// Convert the request information into a string for easy locating

Contentdata: = '';

For longindex: = 0 to fcontentlength-1 do

Begin

Contentdata: = contentdata + CHR (byte (fcontentdata [longindex]);

If fcontentdata [longindex] = 0 Then break; // 0 indicates that the content ends.

End;

3. Get the delimiter and upload file name

// Obtain the boundary of the form field

Longpos: = pos (#13 #10, contentdata); // enter the location of the Line Break

Fdelimeter: = copy (contentdata, 1, longPos-1); // content before this location is a separator

// Obtain the file name with the source path. In the request information, the file name is

// Filename = "path/FILENAME" format Storage

Strtemp: = 'filename = "'; // the file name is after" filename = ""

Longpos: = pos (strtemp, contentdata); // obtain the "filename =" "Location

If longpos <= 0 then

Begin

Ffilename: = '';

Ffiledatastart: =-1;

Ffiledataend: =-2;

Exit;

End;

// Obtain the content before the next double quotation mark "", that is, the file name with the Source Path

Longpos: = longpos + Length (strtemp );

Strtemp: = '';

For longindex: = longpos to fcontentlength-1 do

If contentdata [longindex] <> '"'Then

Strtemp: = strtemp + contentdata [longindex]

Else break;

Ffilename: = strtemp;

4. Get the start and end positions of file data in the Request Information Content

// The start position of the file data is after the first file name #13 #10 #13 #10

Delete (contentdata, 1, longindex );

Strtemp: = #13 #10 #13 #10;

Ffiledatastart: = longindex + pos (strtemp, contentdata) + Length (strtemp)-1;

// The end position of the file data is before the next #13 #10 and the delimiter.

// Because the file data may contain invalid characters, the POs function cannot be used as the string locating function.

// Locate the next Separator

Ffiledataend: = ffiledatastart;

Intdelimterlength: = length (fdelimeter );

Findendoffiledata: = false;

While ffiledataend <= fcontentlength-intdelimterlength do

Begin

Findendoffiledata: = true;

For alongint: = 0 to intdelimterlength-1 do

If byte (fdelimeter [alongint + 1]) <>

Fcontentdata [ffiledataend + alongint] Then

Begin

Findendoffiledata: = false;

Break;

End;

If findendoffiledata then break;

Ffiledataend: = ffiledataend + 1;

End;

If not findendoffiledata then ffiledataend: = ffiledatastart-1 // The Delimiter is not found.

Else ffiledataend: = ffiledataend-3; // delimiter, skipped #13 #10

End;

(3) transmitting information to ASP programs

After (2), the Upload Component can transmit data to it according to ASP program requirements. Currently, you can provide the following data: client source file name (ffilename, including path) and file size (ffiledataend-ffiledatastart + 1 ).

First, declare the getfilename and getfilesize methods in The TLB design window.

1. Return the client source file name (including path)

// Return the client source file name (including path)

Function tuploadfile. getfilename: olevariant;

Begin

Result: = ffilename; // client source file name (including path)

End;

2. Size of the returned File

// Returns the file size (bytes)

Function tuploadfile. getfilesize: olevariant;

Begin

Result: = ffiledataend-ffiledatastart + 1;

End;

(4) saving files

After (2), the Upload Component can save the file as required by the ASP program. First

The TLB design window declares the following two methods: savefileas and SaveFile.

1. Save the file by the specified file name

// Save the file by the specified file name. The filename parameter is the specified file name. The returned value is true, indicating that the file is saved successfully.

Function tuploadfile. savefileas (filename: olevariant): olevariant;

VaR

Longindex: longint;

Afile: file of byte; // save the file in binary format

Bytedata: byte;

Begin

Result: = true;

Try

Assign (afile, filename );

Rewrite (afile );

For longindex: = ffiledatastart to ffiledataend do

Begin

Bytedata: = byte (fcontentdata [longindex]);

Write (afile, bytedata );

End;

Closefile (afile );

Except

Result: = false;

End;

End;

2. Save the file by default file name

// Save the file according to the default file name and save the file with the same name in the directory on the call page

Function tuploadfile. SaveFile: olevariant;

VaR

Currentfilepath: string;

Begin

// Obtain the directory of the call page

Currentfilepath: = fscriptingcontext. Request. servervariables ['path _ translated '];

Currentfilepath: = extractfilepath (currentfilepath );

// Save the file

Result: = savefileas (currentfilepath + extractfilename (ffilename ));

End;

3. Upload Component application example

In our example, delphiup. htm is the file upload interface, and delphiup. asp is used to upload files.

The delphiup. ASP code is as follows:

<! -- Delphiup. asp: File Upload processing page -->

<HTML>

<% Dim upload, filename

Set upload = server. Createobject ("myupload. uploadfile ")

Filename = upload. getfilename

Response. Write "<br> saving the file" & filename & "..."

If upload. SaveFile then

Response. Write "<br> the file" & filename & "is uploaded successfully. "

Response. Write "<br> the file size is" & upload. getfilesize & "bytes. "

Else

Failed to upload the response. Write "<br> file" & filename. "

End if

Set upload = nothing %>

</Body>

Iv. Notes

1. The size of the DLL file automatically generated by Delphi is 215 kb.

In the interface section of asptypelibrary_tlb.pas, all units in uses except ActiveX are deleted.

Delete all units in uses in myupload_tlb.pas. The size of the generated DLL file can be reduced to 61 KB.

2. The above method is also applicable to CGI programs, but the twebrequest object is used.

The above program is successfully debugged under pwin98 + Delphi3.0 + pws4.0.

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.