JSP multiple File Upload code

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

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 (can directly leverage tested and trusted existing components, avoids duplication of development), but also provides more scalability for JSP applications.

File upload function is very common in the development mode based on B/S. Compared with other development tools, JSP upload support to the file is not perfect, it is not as ASP as the need to use components to complete, and not as PHP as the direct provision of file upload support. The implementation of the JSP implementation file upload is this: using the ServletRequest class of the getInputStream () method to obtain a client sent to the server data flow, and then process the data flow, from the analysis, to get the file on the cross to the server parameters and data, The file data is then stored as a file or inserted into the database. In general, JSP pages do not process the upload function of the file, but put these functions into the servlet or JavaBean to achieve. Using the servlet to complete the file upload examples in some JSP related books are introduced, I introduce here to use Jeanbean is how to complete the file upload. The implementation of file upload in JSP can be implemented by HTTP protocol and FTP protocol in two ways, and there are great differences in the principle of transmission. The following will be combined with the source code to do a brief introduction to their implementation, I believe that readers will gain. The following programs have been debugged. Debugging Environment: Window Server+apache +tomcat4.0,javabean Debugging Environment: Jdk1.4+editplus.

The use of JavaBean in JSP to implement the Web-based file upload function generally requires three kinds of files combined to complete. These three kinds of files are the HTML page files that provide the interface, the JavaBean JSP file that implements the upload function, and the Java class file that implements the JavaBean. Below I will focus on the use of HTTP protocol and FTP protocol to achieve file upload function of the JavaBean part.

1 using HTTP protocol to upload multiple files

In the past HTML, the form does not implement file upload, which limits some of the functionality of some Web pages. The RFC1867 specification, which implements the form-based file upload in HTML, expands the form to add a table cell element 〈input type=file>. By using this element, the browser automatically generates an input box and a button that allows the user to fill in the local file name and path name, and the button lets the browser open a File selection box for the user to select the file. The specific form implementation is as follows:

When you select the Paste file to enter the absolute path of the local file directly, the form's Action property value is *.jsp, which means that the request (including the uploaded file) will be sent to * ... JSP files. In this process, a file upload is actually implemented in HTTP mode. The upload of files from client to server is supported by the Common Gateway Interface (CGI) of the HTTP protocol. This upload mode requires both the browser and webserver to support Rfc1867. JavaBean through the ServletRequest class of getInputStream () method to obtain a client sent to the server data flow, analysis uploaded file format, according to the results of the analysis of multiple files to output server-side target files. The function of the 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
{.........}
......
}

Initializes the running environment of the servlet through the Initialize () method. Use the upload () method to obtain the input stream, analyze the format of the uploaded file, and assign the properties of each uploaded file to multiple instances of the file class, which are managed by the files class. The file class calls its save () method based on the properties of each file to output multiple files sequentially to the server-side destination file. where the upload () method is critical to analyze the format of the http1.1 protocol transfer file. After testing, we derive the format of the transfer stream file, which is useful for understanding the upload () method. For example, upload my document t.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 Documents t.sql"
Content-type:text/plain
Source file Contents
CREATE TABLE info (
Content image null);
Separator for next file
-----------------------------7d226137250336
Content-disposition:form-data; Name= "FILE2"; Filename= ""
Content-type:application/octet-stream
-----------------------------7d226137250336

From the above file we can see that the HTTP protocol when uploading multiple files, is to put all the files into the input stream and a certain separator to distinguish. 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 actual data of the file's location. The point to note here is that the separator is random and is all the characters before the first carriage return of the stream file.

The implementation process for the Upload () method is to 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.");}

This uses a multiple-byte read method in the loop, which reads the data continuously until the array fills up. If a file is fully available, all the bytes of the file will be available. However, because the network speed is usually much slower than the CPU, it is easy for the program to empty the network buffer before all data arrives. In fact, the Multi-Byte Read method returns 0 when it attempts to read data from a temporarily empty but open network buffer, which means that no data exists but the network stream is not closed. In this case, the Single-byte method will prevent the execution of the program from running, so multibyte behavior is better than the one-byte read () method. The next step is to parse the byte array M_binarray. Find the separator first, use the Getdataheader () method to return the value of the file information header, from which to determine the full pathname of the source file, the extension of the source file and the source file content format, and use the Getdatasection () method to return the content data of the file. and record the location of the file data in the byte array. It then generates an instance of the file class and places the full pathname, the source file extension, the source file content format, and the file's content data to the properties of the file class instance. Locate the next separator, and continue to repeat the process until the analysis is complete.

2 upload of multiple files using FTP protocol

The FTP protocol is the protocol used to transfer files on the Internet, and provides a standard for transferring files on the Internet. Implementing this functionality in Java is done with the help of the FtpClient class. The implementation of the process: first with the FTP server to establish a connection; initialization file transmission mode, including ASCII and binary two ways; output the file to the file input stream fileinputstream; The data in FileInputStream is read into a byte array The data in the byte array writes to the output stream Telnetoutputstream (writes the data to a network link by using the Write method). A file with the same name as the source file is copied to the server side. In the JavaBean of this example, the file upload process is done through the connectserver (), upload (), and Closeconnect () three methods. 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)
{
IP address of the SERVER:FTP server; User: Logon to the FTP server username
Password: the password for the username to log on to the FTP server; path:ftp the path on the 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);
The name of the file is parsed from filename as the name of the target file, and the method implementation does not give
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 connection to the FTP server, opens the remote FTP server using the FtpClient openserver (String server) method, and then uses ftpclient login (user, Password) method to log on to the server. There are two ways to log on to a remote FTP server, one is to sign in to the user and the other is to log on anonymously. The former requires users to register first as a server customer, the server will give customers a login account and password, based on the account and password linked to the server. The latter requires users to use special username "annoymous" and "Guest" with limited access to the public files of remote hosts without registering, and many systems now require users to send their email addresses as passwords. For security purposes, most anonymous FTP hosts allow only remote users to download files, not uploads, which depend on the settings of the FTP server. Users can choose to use two methods according to the actual situation. Use the FtpClient binary () method to initialize the transfer mode in bytes after the login is completed. Upload () completes the file upload function. Creates a file input stream FileInputStream The source file, writes the input stream to a byte array, and writes the data from the byte array to a network link using the Telnetoutputstream write method. Because Telnetoutputstream is opening a file on the FTP server, the data is written to the destination file, which completes the file upload. Closeconnect () requires a disconnect from the server.

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.