Copy upload file, upload file to server specified location, note that submitting form needs to develop enctype type. The specific code is as follows:
Servlet Code:
/** 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 a 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 in which the files are temporarily in the 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 copy and upload 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 files!") ");
}
}
}
} catch (Fileuploadexception e) {
System.out.println ("File upload failed!") ");
E.printstacktrace ();
}
}
servlet configuration: Web.xml
<?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:
<body>
<form method= "POST" action= "Servlet/myservlet" enctype= "Multipart/form-data" >
<font color= "Blue" > can publish Zip files directly </font> <br/>
Publishing Process file: <input type= "file" name= "Processdef"/>
<input type= "Submit" value= "Deployment"/>
</form>
</body>