Servlet code:
Copy codeThe Code is as follows:
/** Directly retrieve the uploaded File */
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
String targetPath = request. getRealPath (request. getContextPath (); // target storage path, under the 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 () {// determines whether the file or text information is used.
System. out. println ("form parameter name:" + file. getFieldName () + ", form parameter value:" + file. getString ("UTF-8 "));
} Else {
If (file. getName ()! = Null &&! File. getName (). equals ("") {// determines whether a file is selected
File sFile = new File (file. getName (); // construct a temporary object. The File is saved in the server's memory.
File tFile = new File (targetPath, sFile. getName ());
If (tFile. exists ()){
System. out. println ("file of the same name has been uploaded! ");
} Else {
// FileUtils. copyFileToDirectory (sFile, tFile); // directly copy and upload the file to the server, and automatically generate the directory on the machine. The directory name is the same as the name of the uploaded file.
FileUtils. copyFile (sFile, tFile); // directly copy and upload the file to the server, and generate the target file directly at the specified location
System. out. println ("File Uploaded successfully ");
If (tFile. isDirectory () {// Delete the uploaded file
FileUtils. deleteDirectory (tFile );
} Else if (tFile. isFile ()){
TFile. delete ();
}
System. out. println ("File deleted successfully ");
}
} Else {
System. out. println ("file not selected! ");
}
}
}
} Catch (FileUploadException e ){
System. out. println ("File Upload Failed! ");
E. printStackTrace ();
}
}
Servlet configuration: web. xml
Copy codeThe Code is 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 codeThe Code is as follows:
<Body>
<Form method = "post" action = "servlet/MyServlet" encType = "multipart/form-data">
<Font color = "blue"> zip files can be directly published </font> <br/>
Release Process file: <input type = "file" name = "processDef"/>
<Input type = "submit" value = "deployment"/>
</Form>
</Body>