Servlet Code:
Copy Code code as follows:
/** directly to upload file */
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
String TargetPath = Request.getrealpath (Request.getcontextpath ()); Target storage path, under Server Deployment directory
Request.setcharacterencoding ("UTF-8");
try {
Defaultfileitemfactory factory = new Defaultfileitemfactory ();
Diskfileupload up = new Diskfileupload (factory);
list<fileitem> ls = up.parserequest (request);
for (Fileitem File:ls) {
if (File.isformfield ()) {//judgment is file or textual information
System.out.println ("Form parameter name:" + file.getfieldname () + ", form parameter value:" + file.getstring ("UTF-8"));
} else {
if (file.getname ()!= null &&!file.getname (). Equals ("")) {//Determine if the file is selected
File Sfile = new file (File.getname ());//Constructs a temporary object that is currently in memory of the server
File Tfile = new file (TargetPath, Sfile.getname ());
if (tfile.exists ()) {
System.out.println ("file with the same name has been uploaded!") ");
}else{
Fileutils.copyfiletodirectory (Sfile, Tfile)//directly copied and uploaded to the server, automatically generated on the machine directory, directory name and upload file name consistent
Fileutils.copyfile (Sfile, tfile); Copy and upload files directly to the server and generate target files directly at the specified location
System.out.println ("File upload successful");
if (Tfile.isdirectory ()) {//delete upload file
Fileutils.deletedirectory (Tfile);
else if (Tfile.isfile ()) {
Tfile.delete ();
}
SYSTEM.OUT.PRINTLN ("File deletion succeeded");
}
} else {
System.out.println ("Did not choose to upload file!") ");
}
}
}
catch (Fileuploadexception e) {
System.out.println ("File upload failed!") ");
E.printstacktrace ();
}
}
Servlet configuration: Web.xml
Copy Code code as follows:
<?xml version= "1.0" encoding= "UTF-8"?>
<web-app version= "2.5"
Xmlns= "Http://java.sun.com/xml/ns/javaee"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>test. Myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/servlet/MyServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
HTML page:
Copy Code code as follows:
<body>
<form method= "POST" action= "Servlet/myservlet" enctype= "Multipart/form-data" >
<font color= "Blue" > can directly publish zip file </font> <br/>
Publish process file: <input type= "file" name= "Processdef"/>
<input type= "Submit" value= "Deployment"/>
</form>
</body>