Two Methods for uploading multiple files using JavaBean

Source: Internet
Author: User
Tags file separator remote ftp server ftp protocol

Abstract: This article introduces two methods for uploading multiple files using JavaBean, namely http and ftp. First, it describes the basic format for transmitting multiple files over http and the detailed process for uploading. Then, it briefly introduces how to use the ftpclient class to implement ftp-based uploading, finally, the two methods are compared.

Keywords: JavaBean, http, ftp, ftpclient

JavaBean is a Java-based software component. JSP provides comprehensive support for the integration of JavaBean components in Web applications. This support not only shortens the development time (you can directly use tested and trusted existing components to avoid repeated development), but also brings more scalability to JSP applications.

The file upload function is very common in the B/S-based development mode. Compared with other development tools, JSP does not provide perfect support for file upload. It does not need to be completed by using components as ASP does, it does not directly provide file upload support as PHP does. JSP implements File Upload by using the getInputStream () method of the ServletRequest class to obtain the data stream sent from a client to the server, and then process the data stream, analyze and obtain the parameters and data that are uploaded to the server, and store the file data as a file or insert it into the database. In general, JSP pages do not process File Upload functions, but place these functions in Servlet or JavaBean for implementation. Examples of using Servlet to upload files are described in some JSP related books. Here I will introduce how to upload files using JeanBean. Two methods can be used to upload files in JSP: HTTP and FTP. The two methods differ greatly in the transmission principle. The following is a brief introduction to their implementation based on the source code. I believe that readers will gain some benefits. The following programs have been debugged. Debugging environment: window 2000 server + Apache + tomcat4.0, and JavaBean debugging environment: JDK1.4 + Editplus.

To Use JavaBean in JSP to implement the Web-based file upload function, three types of files are generally required. These three types of files are HTML page files on the interface, JSP files of JavaBean that complete the call to implement the upload function, and Java class files that implement JavaBean. I will focus on the JavaBean section that implements the file upload function using HTTP and FTP protocols.

1. Use HTTP to upload multiple files

In the past Html, forms cannot be used to upload files, which limits the functionality of some web pages. RFC1867 (form-based file upload in Html) expands the form and adds a form Element <input type = file>. By using this element, the browser automatically generates an input box and a button. The input box allows you to enter the local file name and path name. The button allows the browser to open a file selection box for users to select a file. The specific form implementation is as follows:

<Forpolichod = "POST" ACTION = "*. jsp" ENCTYPE = "multipart/form-data">
<Input type = "FILE" NAME = "FILE1" SIZE = "50"> <BR>
<Input type = "SUBMIT" VALUE = "Upload">
</FORM>

After the file is pasted, enter the absolute path of the local file. The form's action attribute value is *. jsp, which means that the request (including the uploaded file) will be sent *.. jsp file. In this process, an HTTP file is actually uploaded. The upload of files from the client to the server is supported by the general Gateway Interface (CGI) of the HTTP protocol. This upload method requires that both the browser and WEBServer support Rfc1867. JavaBean uses the getInputStream () method of the ServletRequest class to obtain the data stream sent by a client to the server, analyze the file format uploaded, and output multiple files to the target file on the server in sequence based on the analysis results. In this example, the function of JavaBeande 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 the Servlet runtime environment using 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 instances for processing. These File instances are managed by the Files class. The File class calls its save () method based on the properties of each File to output multiple files to the target File on the server in sequence. The upload () method is the key for analyzing the format of the file transmitted by http1.1. After testing, we can obtain the format of the Transfer Stream file, which is useful for understanding the upload () method. For example, upload my document \ tt.txt. The format is as follows:

// File Separator
----------------------------- 7d226137250336
// File Information Header
Content-Disposition: form-data; name = "FILE1"; filename = "C: \ Documents ents and Settings \ Administrator. TIMBER-4O6B0ZZ0 \ My Documents ents \ tt. SQL"
Content-Type: text/plain
// Source file content
Create table info (
Content image null );
// Delimiter of the 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 through HTTP, all files are put into the input stream and are differentiated by certain delimiters. In fact, the upload () method is to analyze the above file and determine the content of the separator, the content format of each file, the complete path name of the file, and the start and end location of the actual data of the file. Here, we need to note that the separator is random and it is all characters before the first carriage return in the Transfer Stream file.

The Upload () method is implemented by first outputting the input stream file to the byte array m_binArray and implementing it 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 .");}

Here, the multi-byte reading method is used in the loop. The above loop continues to read data until the array is filled up. If a file can be completely obtained, all the bytes of the file can be obtained. However, because the network speed is usually much slower than the CPU speed, it is easy for the program to clear the network buffer before all the data arrives. In fact, when you try to read data from a temporarily empty but open network cache, The multibyte read method returns 0, indicating that no data exists but the network stream is not closed. In this case, the single-byte method will stop running programs, so the multi-byte behavior is better than the single-byte read () method. Next we will analyze the byte array m_binArray. First, find the delimiter. Use the getDataHeader () method to return the value of the file information header to determine the complete path name of the source file, the extension of the source file, and the format of the source file content. Use getDataSection () method to return the content data of the file, and record the starting and ending position of the file data in the byte array. Then, a File class instance is generated, and the complete path name of the File, the extension of the source File, the content format of the source File, and the start and end locations of the File content data are placed in the attributes of the File class instance. Find the next separator and repeat the above process until the analysis is complete.

2. Use FTP to upload multiple files

The FTP protocol is used to transmit files over the Internet, which specifies the criteria for mutual transfer of files over the Internet. The FtpClient class is used to implement this function in java. Specific implementation process: first establish a connection with the FTP server; initialize the file transmission mode, including ASCII and BINARY; output the file to the file input stream FileInputStream; data in FileInputStream is read into the byte array; data in the byte array is written to the output stream TelnetOutputStream (data is written to a network link using the write method ). In this way, a file with the same name as the source file is copied to the server. In this example, JavaBean uses the connectServer (), upload (), and closeConnect () Methods to upload files. 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: user name used to log on to the FTP server
// Password: password of the username used to log on to the FTP server; path: 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 );
// Extract the file name from filename as the name of the target file. The specific implementation method is not provided.
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 [1, 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 () is used to establish a connection with the FTP server. Use the FtpClient openServer (string server) method to open the remote FTP server, and then use the FtpClient login (user, password) method to log on to the server. You can log on to the remote FTP server in two ways: registering a user to log on, and logging on anonymously. The former requires the user to register as a server customer first, the server will give the customer a login account and password, according to the account and password to connect to the server. The latter requires users to use special user names "annoymous" and "guest" without registration to access public files of remote hosts. Many systems require users to use the Email address as a password. For security purposes, most anonymous FTP hosts generally only allow remote users to download files, rather than upload files, depending on the settings of the FTP server. You can select two methods based on your actual situation. After logon, use the FtpClient binary () method to initialize the transmission mode in bytes. Upload () completes the file upload function. Create the file input stream FileInputStream of the source file, write the input stream to the byte array, and write the data in the byte array to a network link using the write method of TelnetOutputStream. Because TelnetOutputStream opens a file on the FTP server, the data is written to the target file, which completes the file upload. CloseConnect () must be disconnected from the server.

The above is only the process of uploading a single file. If there are multiple files, you can call this upload process 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 program, and the security settings on the server are complicated. using the HTTP protocol to upload files is a server application, security Settings are relatively simple. In addition, it is found that the FTP upload speed is dozens or even hundreds of times higher than the HTTP upload speed when large files are transmitted, however, the transfer of files smaller than 1 MB is a little slower than the HTTP upload method. Therefore, the two transmission modes have their own advantages. Please do your best according to your situation. If you have any questions or need other source code, please contact me!

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.