JavaBean implements two methods uploaded by multiple files

zhaozj2021-02-12  141

JavaBean implements two methods uploaded by multiple files

Wang Xinfang Liu Jie

Beijing University of Technology School of Computer

Summary: This article introduces two methods uploaded by JavaBean to implement multiple files, namely HTTP protocol and FTP protocol implementation. First, the HTTP protocol transmits the basic format of multiple files and implements the uploaded detailed process of upload. Then, the Upload of the FTP method is implemented using the FTPClient class, and finally compares these two methods.

Keywords: javabean, http, ftp, ftpclient

JavaBean is a Java-based software component. JSP provides perfect support for integrating Javabean components in web applications. This support not only reduces development time (can directly utilize test and trusted components, avoid repeated development), but also bring more scalability for JSP applications.

The upload function of the file is very common in B / S development model. Compared with other development tools, JSP's upload support for files is not perfect. It is neither a component that must be used as the ASP, and it is not as supported by file uploads like PHP. The implementation of the JSP implementation file upload is this: use the GetInputStream () method of the servletRequest class to get a client to send a data stream to the server, then process this data stream, analyze, get the file upload to pass to the server to each parameter and Data, then store the file data into a file or insert into the database. Usually the upload function of the file is not processed in the JSP page, but put these functions into the servlet or JavaBean. Examples uploaded using servlet have introduced in some JSP related books, I introduced how Jeanbean is uploaded using Jeanbean. The upload of the file in JSP can be implemented in two ways, namely HTTP protocol and FTP protocol implementation, and the two have great differences in the principle of transmission. The combined source code will be briefly introduced below, and believe that the reader will gain from it. The following procedures have been debugged. Debugging environment: Window 2000 Server Apache Tomcat4.0, JavaBean Debugging Environment: JDK1.4 Editplus.

Using JSP Using JavaBean to implement Web-based file upload feature generally require three files to complete. These three files are the HTML page files that provide interfaces, and complete the JSP files for JavaBeans that implement the upload function and the Java's Java's class files. Here I will focus on the JavaBean section that implements the file upload function using the HTTP protocol and the FTP protocol.

1 Using the HTTP protocol to implement multiple files upload

In the past HTML, the form cannot be uploaded, which limits some of the functions of some web pages. RFC1867 specification (ie, implementing form-based file upload), an extended form is extended, adding a form element . By using this element, the browser automatically generates an input box and a button, the input box can fill in the local file name and path name, buttons allow the browser to open a file selection box for the user to select a file. The specific form is achieved as follows:


When the paste file is selected, enter the absolute path of the local file directly, the action attribute value of the form is * .jsp, which means the request (including the uploaded file) will be sent to the * .. JSP file. In this process, the file upload of the HTTP mode is actually implemented. The file from the client to the server is supported by the Universal Gateway Interface (CGI) of the HTTP protocol. This kind of uploading requires both browser and Webserver to support RFC1867. JavaBean obtains a client-side data stream to the server through the GetInputStream () method of the servletRequest class, analyzing the uploaded file format, and outputs multiple files in the target file of the server side based on the analysis results. The functionality of Javabeande in this example is implemented by the TestupLoad class. The framework of the Testupload class is as follows:

Public Class Testupload

{

Public testupload () {...}

Public Final Void Initialize (ServletConfig Config) Throws ServletException

{M_application = config.getServletContext ();

Public void Upload () THROWS TESTUPLOADEXCEPTION, IOEXCEPTION, ServletException

{.........}

Private void getDataSection () {.........

Private void getDataHeader () {.........

Public int Save (String destpathname)

Throws SmartUploadException, IOException, ServletException

{.........}

......

}

Initialize () method initializes the service environment of the servlet. Use the UPLOAD () method to get the input stream, and analyze the format of the upload file, and assign the properties of each upload file to multiple File class instances, which are managed by Files class. The File class calls its Save () method according to the attributes of each file, sequentially outputs multiple files in the target file of the server. Where the UPLOAD () method is the key to analyze the format of the HTTP1.1 protocol transfer file. After testing, we got a format of transport stream files, which is useful to understand the UPLOAD () method. For example, upload my document /tt.txt file. The format is as follows:

// File separator

---------------------------- 7D226137250336

// File information head

Content-disposition: form-data; name = "file1"; filename = "c: / documents and settings / administrator.timber-4o6b0zz0 / my documents / tt.sql" Content-Ty: Text / Plain

// Source file content

CREATE TABLE INFO (Content Image Null);

/ / Delivery of the next file

---------------------------- 7D226137250336Content-disposition: form-data; name = "file2"; filename = "" Content-Type : Application / OcTet-Stream ---------------------------- 7D226137250336 From the above document we can see that the HTTP protocol is uploaded multiple When the file is set to all files all in the input stream and distinguish between a certain separator. In fact, the UPLOAD () method is to analyze the above file, determine the content of the separator, the content format of each file, the full path name of the file, and the beginning of the actual data of the file. The point herein is that the separator is random, which is all the characters before the first carrier of the stream file. The implementation process of the UPLOAD () method is: First output the input stream file to the byte array m_binarray, and implement it through the following code.

M_TotalBytes = 1024; TotalRead = 0;

For (; TotalRead

Try

{M_request.getinputStream ();

ReadBytes = m_request.getinputStream (). Read (M_binarray, TotalRead, M_Totalbytes - TotalRead);

("unable to upload.");} ("unable to upload.");}

Here, multi-byte reading methods in cycles are used, and the above cycles continue to read data until the array is filled. If a file can be completely obtained, all bytes of the file can be obtained. However, since the network speed is usually much slower than the CPU, the program is easy to clear the network buffer before all the data arrive. In fact, the multi-byte reading method is attempting to read data from temporary but open network buffers, this method returns 0, which means that there is no data presence but the network stream is not closed. In this case, the single-byte method will prevent the execution of the running program, so the multiple-byte behavior is better than the behavior of the single-byte read () method. Next, the byte array M_BinArray will be analyzed. First find the separator; use the getDataHeader () method to return the value of the file information header, determine the full path name of the source file, the extension of the source file, and the content file content format of the source file; use the getDatasection () method to return the content data of the file, and record The termination location in the byte array is in the byte array. A File class instance is then generated, and the full path name of the file, the extension of the source file, the source file file content format, and the content data of the file content data are placed in the properties of the FILE class instance. Find the next separator and continue to repeat the above process until the analysis is completed.

2 Upload multiple files to achieve multiple files with FTP protocol

The FTP protocol is the protocol used to transmit files on the Internet, which specifies the standards of files transmitted to each other on the Internet. This feature implements this in Java is done with the FTPClient class. Specific implementation process: first establish a connection with the FTP server; in the transmission mode of the file, including ASCII and Binary; output the file to the file input stream FileInputStream; Data reading in the fileInputStream is in the byte array; byte arrays The data write output stream TelnetOutputStream (using the WRITE method to write data to a network link). This is copied to the server side with a file as the source file. The Javabean in this example completes the file upload process through connect Server (), UPLOAD (), and CloseConnect (). Mainly achieved as follows: public class ftpupload

{String filename; string filename1; ftpclient ftpclient;

Public Void ConnectServer (String Server, String User, String Password, String Path)

{

// Server: The IP address of the FTP server; User: User name to log in to the FTP server

// password: Log in to the password of the username of the FTP server; PATH: the path on the FTP server

Try {ftpclient = new ftpclient ();

FTPClient.openserver (Server);

ftpClient.login (User, Password);

System.out.println ("Login Success!");

IF (Path.Length ()! = 0) ftpclient.cd (path);

FTPCLIENT.BINARY ();} catch (ooexception ex) {system.out.println (ex);

}

Public void closeconnect ()

{Try {ftpclient.closeserver ();

} catch (ioexception ex) {system.out.println (ex);}

}

Public void Upload ()

{Filename1 = findfilename (filename);

/ / Analyze the name of the file from FileName, as the name of the target file, the specific method is not given

Try {

TelnetOutputStream OS = ftpclient.put (filename1);

Java.io.file file_in = new java.io.file (filename);

FileInputStream is = new fileinputstream (file_in);

Byte [] bytes = new byte [1024];

INT C;

While ((c = is.read (bytes))! = - 1) {os.write (bytes, 0, c);}

IS.CLOSE (); Os.Close ();

} catch (ioexception ex) {system.out.println (ex);}

}

}

ConnectServer () Completes the function of establishing a connection with the FTP server, open the remote FTP server using FTPClient's OpenServer (String Server) method, and then log in to the server using the FTPClient Login (User, Password) method. There are two ways to log in to the remote FTP server, one is a registered user login, and the other is logged in anonymously. The former asks the user to register as a server, and the server will give the client a login account and password, and connect to the server based on the account number and password. The latter requires users to use special username "AnnoyMous" and "Guest" to access the remote host without registration, and now many systems require users to use the Email address as a password. For security purposes, most anonymous FTP hosts typically only allow remote users to download files, not uploading, which will depend on the setting of the FTP server. Users can choose two ways according to the actual situation. After the login is completed, the binary () method using ftpclient is initialized in the transmission mode as byte. Upload () completes the upload function of the file. Creating a file input stream for a source file FileInputStream, writes the input stream into the byte array, writes the data in the byte array to a network link with the Write method of TelnetOutputStream. Since TelnetOutputStream opens a file on the FTP server, the data is written to the target file, so that the file is uploaded. CloseConnect () requires disconnection with the server. The above is just a single file upload process, and if multiple files can call this upload multiple times. From the above two ways we can see that the upload of multiple files in the FTP protocol is simple and easy to implement. Using FTP protocol Upload files are generally written client programs, the security settings of the server side are more complicated; and upload files with HTTP protocols is the application of the server, relatively simple. And through the test, the FTP upload mode is transmitted to several tens of times or even hundreds of times the HTTP upload mode is transmitted, but it is slightly slower than the HTTP upload mode when transmitting less than 1m. Therefore, two types of transmission methods have their own advantages, and readers should be taken according to their own conditions. If you have any questions or you need the source code of other parts, please contact me!

references:

1. Liao Ruoxue, "JSP Advanced Programming", Machinery Industry Press, 2001.3

2. Huang Quan, Hong Liang, etc., "JSP Senior Programming", Beijing Hope Electronics Press, 2001.10

3. Elliotte Rusty Harold, Liu Donghua, Wang Wei, Tang Tang translated, Java Network Programming, China Electric Press, 2001.8

4. Bruce Eckel, Jingjing Studio Translation, Java Programming, Machinery Industry Press, 1999.4

5. Http://www.jspsmart.com

转载请注明原文地址:https://www.9cbs.com/read-6431.html

New Post(0)