Web File Upload principle

Source: Internet
Author: User
Tags chr

Using web technology to realize B/s (browser/server) structure management system is the development trend of office automation. The management system based on Web technology has been developed rapidly in recent years due to its short development period, independent of user platform, easy to realize interactive application, fast and efficient collection, processing and release of information. ASP technology has become the preferred tool for development management system because of its high development efficiency, good interactivity and strong security.
Many web-based applications involve file upload operations. Common file Upload technology is based on HTTP protocol, based on VB (or Delphi and other programming languages) to develop the file upload components, based on database technology and so on. These methods generally require programmers to be able to master Web technology, database technology or CGI technology or component technology, the requirements of programmers are higher. And this article will introduce the use of ASP technology to directly implement the file upload function, only the programmer can master a single ASP technology, greatly reducing the difficulty of programming.
Comparison of several file upload techniques
1, based on the HTTP protocol
This method requires the programmer to use third-party software, such as Delphi, VB, and so on, in the application of the HTTP protocol first programming, and then the content of the file to be uploaded in the format of the HTTP protocol, and finally send the uploaded request message to the Web server, so as to achieve file upload. Because Delphi and VB can not write a complete Web network program, can only write web small applications, therefore, this method is only used for limited-functionality network applications.
2, based on VB (or Delphi, etc.) development of File upload components
This method uses VB (or Delphi and other programming languages) to develop ASP server components to achieve the specific file upload service. It first uses the ASP form function to upload the file (binary format) from the client to the server side, and then uses the VB development component, the binary file processing, becomes the file which can read and write normally. This method requires the programmer not only to master the ASP language, but also to use the third-party language such as VB to program the components, which increases the difficulty of development.
3, based on database technology
This method has similarities with the previous method. The difference lies in the processing of the uploaded binaries. It uses the database to save the binaries. Whether a small database or a large database provides a data type that stores binary data, it is only possible to store the data in the appropriate fields in the Append chunk way. This method is simple and feasible, but because each upload file size is not the same, therefore, the space of the database will cause a lot of waste, reduce the data access speed, and make the file can only be accessed in the database environment, causing great inconvenience.
Example analysis
However, the use of ASP technology to directly implement the file upload function only requires the programmer to master a single ASP technology can be,
Greatly reduces the difficulty of programming. Below we will show you how to use this method with an example.
1. File Upload Form
The first thing you need to do is write a form that provides the file upload functionality, as shown in the following procedure:
<form action= "upload.asp" Method=post enctype= "Multipart/form-data" >
Upload file: <input type=file name=file1><br>
<input type=submit name=upload value= "Upload" >
</form>
Where the enctype parameter is used to set the MIME encoding of the form, you must set its properties to "Multipart/form-data" when you upload the file (or also include a text box) Upload.asp is a server-side docking received binary file stream processing ASP program, in the later part of this article will introduce its content.
2. Upload file format analysis
Before processing the file, we need to understand the specific format of the uploaded file, by writing the following a simple ASP program to view the binary code:
<%
Filesize=request.totalbytes ' Get the size of the uploaded file
Filedata=request.binaryread (filesize) ' Get binary data for uploaded files
Response.BinaryWrite filedata ' Display binary data on the browser
%>
Analyze the binary code of the uploaded file displayed on the browser, the discovery code consists of four parts (if you upload multiple files or text boxes at the same time, the code is in the order of uploading, the format is the same), each part of the content is separated by a carriage return line symbol:
1) The first part (starting mark)
-----------------------------7d329631b04d4
2) Part II (Description of documents)
Content-disposition:form-data; Name= "File1"; Filename= "C:\Documents and Settings\Administrator\My Documents\invitation.doc" Content-type:application/msword
Here, we can get the file name and absolute path of the uploaded file, and we can get the file type. This information is indispensable for saving files correctly.

3) Part III (contents of the document)
That is, the binary content of the file, slightly.
4) The fourth part (end sign)
-----------------------------7d329631b04d4
Combined with the first and fourth parts, the "-----------------------------7d329631b04d4" (each upload, the value is different) played the role of the separator, it marks the beginning and end of a piece of data (when there are multiple uploads). From the information needed to save the file, we first need to get the file name from the "filename" of the second part of the data, then we need to locate the file's starting position correctly, and finally use ASP technology to save the binary file with the original file name. If you upload multiple content (such as multiple text boxes and files) in the same way, the content of each part is included in the separator, but the text box and file form slightly different, this can be understood by the specific analysis of the binary code.
3, using ASP technology to achieve file storage
Handling of uploaded file code
1) Get the separator code
From the above analysis we already know that the separator plays an important role in splitting multiple data segments (including text boxes and various types of files). As previously analyzed, the separator appears before the first carriage return newline symbol. Therefore, the following procedure allows you to obtain the delimiter code:
<%
NEWLINE=CHRB (& ChrB) ' newline denotes binary carriage return
Filesize=request.totalbytes ' filesize is the size of the upload file
Filedata=request.binaryread (filesize) ' filedata is binary data for uploading files
Divider=leftb (FILEDATA,CLNG (INSTRB (Filedata,newline))-1) ' Divider is a separator
%>
Note: Because the binary bytecode is processed here, all functions are using its binary version, adding "B".
2) Get the contents of the file (or text box)
(1) Pre-function (convert binary strings to string)
Uploading the contents of the file does not need to go through the binary string conversion process, directly save it. However, if you need to extract the contents of a text box or the name of a file, you must convert it. Therefore, it is necessary to write a universal and suitable conversion function for Chinese characters. The following is the function code:
Function Btos (BSTR)
If not be Null (BSTR) Then
For i = 0 to LenB (BSTR)-1
BCHR = MidB (bstr,i+1,1)
If ASCB (BCHR) >127 Then ' kanji is double byte, get two characters to process together
temp = TEMP&AMP;CHR (AscW (MidB (BSTR, I+2, 1) &bchr))
i = i+1
Else
temp = TEMP&AMP;CHR (ASCB (BCHR))
End If
Next
End If
Btos = Temp
End Function
(2) Get the contents of a file (or text box)
In an actual Web application, the upload operation may involve multiple items, such as several text boxes, multiple files, and so on. Files and text boxes are well-differentiated, and the file's data contains the "Filename=" string. Therefore, we write the following general function, which can be used to extract the contents of the file and extract the contents of the text box (binary conversion required):
Function GetData (ByVal Data, ByVal Divider, Final) ' data represents a binary string; divider represents a delimiter; final represents the end position of the data
FILENAME=CHRB (102) &AMP;CHRB () &AMP;CHRB (108) &AMP;CHRB (101) &AMP;CHRB (a) &AMP;CHRB (&AMP;CHRB) 109 (101) &AMP;CHRB (34) The binary representation of the string "filename"
BNCRLF=CHRB (in) &AMP;CHRB (10) ' Binary carriage return
startpos = INSTRB (data,divider) +lenb (divider) +lenb (BNCRLF) ' Start position
Endpos = INSTRB (startpos,data, divider)-lenb (BNCRLF) ' End position
Part1 = content between MidB (data, startpos, Endpos-startpos) ' two delimiters
Firstline = MidB (part1, 1, INSTRB (part1, Bncrlf)-1) ' Description segment before the content
if (INSTRB (firstline,filename) =0) Then ' If text box, get text box string contents
Stemp=midb (PART1,INSTRB (PART1,BNCRLF&AMP;BNCRLF) +lenb (BNCRLF&AMP;BNCRLF), LenB (part1)-INSTRB (part1,bncrlf& BNCRLF) +lenb (BNCRLF&AMP;BNCRLF))
Getdata=btos (stemp)
Else ' If it is a file, obtain the binary content of the file
Getdata=midb (Part1, INSTRB (part1, Bncrlf&bncrlf) +lenb (BNCRLF&AMP;BNCRLF), LenB (part1)
-INSTRB (PART1,BNCRLF&AMP;BNCRLF) +lenb (BNCRLF&AMP;BNCRLF))
End If
Final=endpos
End function
Call the function directly in the program to get the content of the desired file (or text box) as follows:
<%
C (data, divider, position)
%>
3) Get the file name
As previously analyzed, the "filename=" field of the upload file data stream contains the file name and absolute path. In general, we only need to extract the file name in the path, the following is the program code:
<%
Namepos=instrrev (B2s (firstline), CHR) ' Firstline is the description part of the data obtained above, CHR (92)
Indicates "/"
Filename=midb (Firstline,namepos+1,lenb (firstline)-namepos-1) ' Get file name
%>
Using ASP to directly implement file upload function
The traditional ASP programmer can only use the FileSystemObject object to move, copy, delete and so on the text file (. txt), if you need to deal with binary objects, you have to use the methods described earlier in this article to implement. However, the Ado.stream object in ASP now can manipulate both the text object and the binary object (which can be downloaded in http://www.microsoft.com/data), which can be used to directly implement the file upload function in ASP. Below, we will describe the implementation process.
1) Open Stream object
For a Sream object, to save a file, you must save the entire contents of the object. Therefore, we have to create two (or more) stream objects, one of which is the source data stream, that is, the initial binary data is received, and the other is the destination data stream that receives the data from the source stream and eventually saves it as the desired file.
<%
Set Str=server. CreateObject ("ADODB. Stream ") ' str is the source data stream
Str. Mode=3 ' Set open mode, 3 is readable and writable
Str. Type=1 ' Set data type, 1 binary data
Str. Open
Set Desc=server. CreateObject ("ADODB. Stream ") ' desc as the target data stream
Desc. Mode=3
Desc.type=1
Desc. Open
%>
2) replication of content between steam objects
In this section, you must locate the beginning of the file in the source data stream, and find the length of the file content in order to copy the file correctly into the destination data stream, and save the file with the following program code:
<%
Formdata=request.binaryread (request.totalbytes) ' Formdata for all content uploaded
Str. Write Formdata ' assignment source data stream
Str.position=count-lenb (Result)-2 ' position indicates where the file starts
Str.copyto desc, LenB (filecotent) ' LenB (filecontent) indicates the length of the file
Desc. SaveToFile fullpath,2 ' Save the file with the path and name specified FullPath
%>
3) Close Steam Object
When programming is complete, you should close and release the Steam object as follows:
<%
Desc. Close
Set desc=nothing
Str. Close
Set str=nothing
%>

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.