JSP uploads the file to the specified location instance code
- 2020-06-15 10:05:08
- OfStack
Servlet code:
/** Take the uploaded one directly File */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String targetPath = request.getRealPath(request.getContextPath()); // Target storage path, 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 it is a file or text message
System.out.println(" Form parameter name :" + file.getFieldName()+ " , form parameter values :" + file.getString("UTF-8"));
} else {
if (file.getName() != null && !file.getName().equals("")) { // Determine if the file was selected
File sFile = new File(file.getName());// A temporary object is constructed in which the file is temporarily stored in the server's memory
File tFile = new File(targetPath, sFile.getName());
if(tFile.exists()){
System.out.println(" Same name file uploaded! ");
}else{
//FileUtils.copyFileToDirectory(sFile, tFile);// Directly copy and upload to the server, automatically generate the computer directory, directory name and the name of the uploaded file 1 to
FileUtils.copyFile(sFile, tFile); // Directly copy and upload the file to the server, directly generate the target file in the specified location
System.out.println(" File upload successful ");
if (tFile.isDirectory()) { // Delete uploaded files
FileUtils.deleteDirectory(tFile);
} else if (tFile.isFile()) {
tFile.delete();
}
System.out.println(" File deleted successfully ");
}
} else {
System.out.println(" No option to upload files! ");
}
}
}
} catch (FileUploadException e) {
System.out.println(" File upload failed! ");
e.printStackTrace();
}
}
Servlet configuration: ES7en.ES8en
<?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 be published directly zip file </font> <br />
Release process file :<input type="file" name="processDef" />
<input type="submit" value=" The deployment of "/>
</form>
</body>