Common-fileupload components
Download Address: http://jakarta.apache.org/commons/fileupload/
Unzip the zip package after downloading and copy Commons-fileupload-1.0.jar to Tomcat's webapps/your webapp/web-inf/lib/.
Create a servlet
Import java.io.*;
Import java.util.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Import org.apache.commons.fileupload.*;
public class Upload extends HttpServlet {
Private String Uploadpath = "c://upload//"; Directory for storing uploaded files
Private String TempPath = "c://upload//tmp//"; The directory used to store temporary files
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws IOException, Servletexception
{
try {
Diskfileupload fu = new Diskfileupload ();
Set maximum file size, this is 4MB
Fu.setsizemax (4194304);
Set the buffer size, this is 4KB
Fu.setsizethreshold (4096);
To set up a temporary directory:
Fu.setrepositorypath (TempPath);
Get all the files:
List Fileitems = fu.parserequest (request);
Iterator i = Fileitems.iterator ();
Process each file sequentially:
while (I.hasnext ()) {
Fileitem fi = (Fileitem) i.next ();
Gets the file name, which includes the path:
String fileName = Fi.getname ();
if (filename!=null) {
Where you can record user and file information
// ...
Write file A.txt, you can also extract filename from filename:
Fi.write (New File (Uploadpath + "a.txt"));
}
}
Jump to upload Success prompt page
}
catch (Exception e) {
Can jump to error page
}
}
}
When the servlet receives a POST request from the browser, it implements the file upload in the Dopost () method. Here is the sample code:
If you want to read the specified upload folder in the configuration file, you can do so in the Init () method:
public void Init () throws Servletexception {
Uploadpath = .....
TempPath = .....
The folder is created automatically if it does not exist:
if (!new File (Uploadpath). Isdirectory ())
New File (Uploadpath). Mkdirs ();
if (!new File (TempPath). Isdirectory ())
New File (TempPath). Mkdirs ();
}
Configure the servlet, open tomcat/webapps/your webapp/web-inf/web.xml with Notepad, and then create a new one. Typical configurations are as follows:
<?xml version= "1.0" encoding= "Iso-8859-1"?>
<! DOCTYPE Web-app
Public "-//sun Microsystems, INC.//DTD Web application 2.3//en"
"Http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
</web-app>
After you configure the servlet, start Tomcat and write a simple HTML test:
<form action= "FileUpload" method= "post" enctype= "Multipart/form-data" Name= "Form1" >
<input type= "File" name= "file" >
<input type= "Submit" name= "submit" value= "Upload" >
</form>
Note action= "FileUpload" where FileUpload is the Url-pattern specified when the servlet is configured. Reproduced