Abstract: This article introduces two methods for JavaBean to implement multiple file uploads, using http protocol and ftp protocol respectively. First, it describes the basic format of transferring multiple files through http protocol and the detailed process of uploading. Then it briefly introduces the use of ftpclient class to implement ftp upload, and finally compares the two methods.
Keywords: JavaBean, http, ftp, ftpclient
JavaBean is a Java-based software component. JSP provides complete support for integrating JavaBean components in Web applications. This support not only shortens development time (you can directly use existing components that have been tested and trusted, avoiding repeated development), but also brings more scalability to JSP applications.
The file upload function is very common in the B/S-based development model. Compared with other development tools, JSP's support for file upload is not perfect. It neither requires components to complete like ASP, nor does it directly provide support for file upload like PHP. The way JSP implements file upload is as follows: use the getInputStream() method of the ServletRequest class to obtain a data stream sent by the client to the server, and then process this data stream to analyze and obtain the various parameters and parameters passed to the server during the file upload. data and then store the file data in it as a file or insert it into a database. Usually JSP pages do not handle the file upload function, but put these functions into Servlets or JavaBeans to implement. Examples of using Servlet to complete file uploads are introduced in some JSP related books. Here I will introduce how to use JeanBean to complete file uploads. There are two ways to upload files in JSP, namely HTTP protocol and FTP protocol. There are big differences in the transmission principles between the two. The following will give a brief introduction to their implementation based on the source code. I believe readers will gain something from it. The following program has been debugged and passed. Debugging environment: window 2000 server+Apache +tomcat4.0, JavaBean debugging environment: JDK1.4+Editplus.
Using JavaBean in JSP to implement the Web-based file upload function generally requires the combination of three types of files. These three files are respectively the HTML page file that provides the interface, the JSP file that completes the call to implement the upload function of JavaBean, and the Java class file that implements JavaBean. Below I will focus on the JavaBean part that uses HTTP protocol and FTP protocol to implement the file upload function.
1 Use HTTP protocol to upload multiple files.
In the past Html, forms could not upload files, which somewhat limited the functions of some web pages. The RFC1867 specification (that is, form-based file upload in Html) extends the form and adds a form element <input type=file>. By using this element, the browser will automatically generate an input box and a button. The input box allows the user to fill in the local file name and path name, and the button allows the browser to open a file selection box for the user to select a file. The specific form implementation is as follows:
<FORMMETHOD="POST" ACTION="*.jsp" ENCTYPE="multipart/form-data">
<INPUT TYPE="FILE" NAME="FILE1" SIZE="50"><BR>
<INPUT TYPE="SUBMIT" VALUE="Upload">
</FORM>
When you choose to paste the file, enter the absolute path of the local file directly. The action attribute value of the form is *.jsp, which means that the request (including the uploaded file) will be sent to the *..jsp file. In this process, file upload via HTTP is actually implemented. Uploading of files from client to server is supported by the Common Gateway Interface (CGI) of the HTTP protocol. This upload method requires that both the browser and WEBServer support Rfc1867. JavaBean obtains a data stream sent by the client to the server through the getInputStream() method of the ServletRequest class, analyzes the uploaded file format, and outputs multiple files to the target file on the server side in sequence based on the analysis results. The function of JavaBeande in this example is specifically 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 the Servlet's running environment through the initialize() method. Use the upload() method to obtain the input stream, analyze the format of the uploaded file, and assign the attributes of each uploaded file to multiple File class instances for processing. These File class instances are managed by the Files class. The File class calls its save () method according to the attributes of each file to output multiple files to the target file on the server side in sequence. The upload() method is the key, used to analyze the format of files transmitted by the http1.1 protocol. After testing, we get the format of the transport stream file, which is useful for understanding the upload() method. For example, upload the My Documentstt.txt file. The format is as follows:
//File separator
--------------------------7d226137250336
//File information header
Content-Disposition: form-data; name="FILE1"; filename="C:Documents and SettingsAdministrator.TIMBER-4O6B0ZZ0My Documentstt.sql"
Content-Type: text/plain
//Source file content
create table info(
content image null);
//Delimiter of next file
--------------------------7d226137250336
Content-Disposition: form-data; name="FILE2"; filename=""
Content-Type: application/octet-stream
--------------------------------7d226137250336
From the above files we can see that when uploading multiple files, the HTTP protocol All are put into the input stream and distinguished by certain delimiters. In fact, the upload() method is to analyze the above file and determine the content of the delimiter, the content format of each file, the full path name of the file, and the beginning and end of the actual data of the file. One thing to note here is that the delimiter is random, it is all characters before the first carriage return character of the transport stream file.
The implementation process of the Upload() method is: first output the input stream file to the byte array m_binArray, which is implemented through the following code.
m_totalBytes=1024; totalRead=0;
for(; totalRead < m_totalBytes; totalRead += readBytes)
try
{ m_request.getInputStream();
readBytes = m_request.getInputStream().read(m_binArray, totalRead, m_totalBytes - totalRead);
}catch(Exception e){ throw new SmartUploadException("Unable to upload.");}
The multi-byte reading method in the loop is used here. The above loop continuously reads data until the array is filled. If a file can be fully retrieved, all bytes of the file can also be retrieved. But because the network speed is usually much slower than the CPU, it is easy for the program to clear the network buffer before all the data arrives. In fact, the multibyte read method will return 0 when trying to read data from a temporarily empty but open network buffer, which means that no data exists but the network stream has not been closed. In this case, the single-byte method will prevent the execution of the running program, so the behavior of the multi-byte method is better than that of the single-byte read() method. Next the byte array m_binArray will be analyzed. First find the delimiter; use the getDataHeader() method to return the value of the file information header, from which the full path name of the source file, the source file extension and the source file content format are determined; use the getDataSection() method to return the file content data and record it The starting and ending positions of the file data in the byte array. Then generate a File class instance, and put the full path name of the file, the extension of the source file, the source file content format, and the starting and ending positions of the file's content data into the attributes of the File class instance. Find the next delimiter and continue repeating the above process until the analysis is completed.
2 Use the FTP protocol to upload multiple files.
The FTP protocol is a protocol used to transfer files on the Internet. It stipulates the standards for mutual transfer of files on the Internet. Implementing this function in java is accomplished with the help of the FtpClient class. Specific implementation process: first establish a connection with the FTP server; initialize the file transmission method, including ASCII and BINARY; output the file to the file input stream FileInputStream; read the data in the FileInputStream into a byte array; into the byte array The data is written to the output stream TelnetOutputStream (use the write method to write the data to a network link). In this way, a file with the same name as the source file is copied to the server. In this example, the JavaBean completes the file upload process through three methods: connectServer(), upload(), and closeConnect(). The main implementation is as follows:
public class ftpUpload
{ String filename;String filename1;FtpClient ftpClient;
public void connectServer(string server,string user,string password,string path)
{
//server: IP address of the FTP server; user: username to log in to the FTP server
//password: the password of the username to log in to 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 (IOException 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 and use it 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, uses FtpClient's openServer(string server) method to open the remote FTP server, and then uses FtpClient's login(user, password) method to log in to the server. There are two ways to log in to the remote FTP server, one is to log in as a registered user, and the other is to log in anonymously. The former requires the user to first register as a client of the server. The server will give the user a login account and password, and connect to the server based on the account and password. The latter requires users to use the special usernames "annoymous" and "guest" without registering to have restricted access to public files on remote hosts. Many systems now require users to use their email address as a password. For security purposes, most anonymous FTP hosts generally only allow remote users to download files, but not upload them. This will depend on the settings of the FTP server. Users can choose to use two methods according to actual conditions. After logging in, use the binary() method of FtpClient to initialize the transmission mode to byte mode. upload() completes the file upload function. Create the file input stream FileInputStream of the source file, write the input stream into the byte array, and use the write method of TelnetOutputStream to write the data in the byte array to a network link. Since TelnetOutputStream opens a file on the FTP server, the data is written to the target file, thus completing the file upload. closeConnect() requires disconnecting from the server.
The above is only the process of uploading a single file. If there are multiple files, this upload process can be called multiple times. From the above two methods, we can see that using the FTP protocol to upload multiple files is relatively simple and easy to implement. Using the FTP protocol to upload files is generally a client-side program, and the server-side security settings will be more complicated; while using the HTTP protocol to upload files is a server-side application, and the security settings will be relatively simple. And through testing, it was found that the FTP upload method is dozens or even hundreds of times faster than the HTTP upload method when transmitting large files, but it is slightly slower than the HTTP upload method when transmitting files smaller than 1M. Therefore, both transmission methods have their own advantages. Readers are advised to act according to their own circumstances. If you have any questions or need the source code of other parts, please contact me!