Servlet+Jsp realize the upload function of pictures or files specific ideas and codes

  • 2020-06-07 05:10:08
  • OfStack

Now whether it is blog forum or enterprise office, can not do without the sharing of resources. By uploading files and sharing them with others, we can achieve extensive communication and exchange among the public. We can not only gain more knowledge and experience from them, but also achieve self-improvement and improvement through feedback from others.

I'm going to show you the 1 upload feature in the web project, so how does a file get sent locally to the server? Watch me speak slowly:
First, we create a new web project, creating a new upload folder in the WebRoot directory of the project, so that when we deploy the project to the server, the server will also generate an upload folder to hold the uploaded resources.

Then, create a new jsp file in the WebRoot directory. The main function of the implementation is to select the uploaded file and submit it to servlet for processing
The detailed code is as follows: 1 form sends file information to the specified servlet via post
 
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<base href="<%=basePath%>"> 
<title>My JSP 'upload.jsp' starting page</title> 
<meta http-equiv="pragma" content="no-cache"> 
<meta http-equiv="cache-control" content="no-cache"> 
<meta http-equiv="expires" content="0"> 
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
<meta http-equiv="description" content="This is my page"> 
<!-- 
<link rel="stylesheet" type="text/css" href="styles.css"> 
--> 
</head> 
<body> 
<form action="/upload/UpLoad" method="post" enctype="multipart/form-data"> 
 Please select the image or file to upload :<input type="file" name="fileName"/><input type="submit" value=" upload "/> 
</form> 
</body> 
</html> 

As you can see, we submitted the data to upload/UpLoad under the project.
From there, let's write this servlet -- UpLoad.java
 
package load; 
import java.io.File; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.List; 
import javax.servlet.ServletContext; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
public class UpLoad extends HttpServlet { 
@SuppressWarnings("unchecked") 
@Override 
protected void service(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException { 
req.setCharacterEncoding("utf-8"); 
resp.setContentType("text/html;charset=utf-8"); 
// Provides configuration information for parsing classes  
DiskFileItemFactory factory = new DiskFileItemFactory(); 
// Create an instance of the parse class  
ServletFileUpload sfu = new ServletFileUpload(factory); 
// Start parsing  
sfu.setFileSizeMax(1024*400); 
// Data in each form field is encapsulated into 1 A corresponding FileItem On the object  
try { 
List<FileItem> items = sfu.parseRequest(req); 
// Distinguish form fields  
for (int i = 0; i < items.size(); i++) { 
FileItem item = items.get(i); 
//isFormField for true , indicates that this is not a file upload form field  
if(!item.isFormField()){ 
ServletContext sctx = getServletContext(); 
// Gets the physical path to the file  
//upload Under some folder   Get current online users   Locate the appropriate folder  

String path = sctx.getRealPath("/upload"); 
System.out.println(path); 
// Get the file name  
String fileName = item.getName(); 
System.out.println(fileName); 
// The method is available on some platforms ( The operating system ), It will return the path + The file name  
fileName = fileName.substring(fileName.lastIndexOf("/")+1); 
File file = new File(path+"\\"+fileName); 
if(!file.exists()){ 
item.write(file); 
// Record the name of the uploaded image in the database  

resp.sendRedirect("/upload/ok.html"); 
} 
} 
} 
} catch (Exception e) { 
e.printStackTrace(); 
} 

} 
} 

Since the code has been annotated in detail, I believe you can also basically upload this process. One thing to note is the setting of the size of the parse instance space. We want the uploaded file not to be infinite, so set
 
.setFileSizeMax(1024*400); 

Here we can also set it to a condition to submit an error message to the page when the file is larger than the maximum value. In addition, you can read the suffix of the selected file to filter out the types that can be uploaded. You can extend this code and not go into details.

Send the correct files to the server's upload folder via servlet. Note here that if you later remove the project from tomcat, these files will be deleted automatically.

Once the upload is complete, redirect the page to the upload success page ok.html. When the user sees this page, you have realized the file upload function.

Related articles: