Simple implementation of java image file upload function

  • 2020-12-16 05:56:45
  • OfStack

Generally speaking, there are two ways to upload images, one is to write the image files to the database, the other is to save to the server file directory. The image file written to the database needs to be converted into the format of 2-base stream, which occupies more database space and is suitable for the storage of a small number of images, such as some small ICONS in the system. The advantage of writing to the database is that it is relatively safe and not easy to be deleted by users accidentally.

If you're storing a lot of images, the usual thing to do is to store them in a folder on the server. And there are many ways to complete the upload, you can do it by streaming, you can do it by ftp, fileupload here.

With the different size of the system, the processing of the image file is not the same. If the number of images in the system is not very large, you can directly store all images in the same directory. If the accumulation of more pictures, according to the material classification of the picture of the corresponding classification storage, this will save 1 some in the disk to find the file time.

Picture upload to the file, you can directly upload the picture to the directory, you can also write the image file name, file path to the database, you can also create a dynamic file path in the program. If the company requires the image to be stored on a dedicated server, it is appropriate to write the file path. It is relatively easy to deal with 1 picture for 1 material (material). If there are multiple images, they need to be recycled. In the first aspect, we need to deal with the dynamic display of the image; in the other aspect, we need to check whether the name of the image file is repeated. In addition, the picture processing (upload, delete, modify) needs to cooperate with the transaction.

The following focuses on the use of fileupload image upload the most basic implementation.

1. file tag is used in the front end:


<input name = "fileName" type ="file" class ="text1" size ="40" maxlength="40"> 

2. Set the FORMAT of enctype: multipart/ ES26en-ES27en


<form name="itemForm" target="_self" id="itemForm" method="post" action="servlet/item/FileUploadServlet" enctype="multipart/form-data" > 

Note on enctype="multipart/ ES34en-ES35en ":

When this format is used in jsp, the corresponding Servlet cannot use ES41en.getParameter () to get parameters. The parseRequest method of ServletFileUpload object is used to parse the data in the request object first, and then the isFormField flag of the parsed element is used to coordinate with the getFieldName method to get data.

3. Realization of FileUploadServlet:


package com.bjpowernode.drp.basedata.web; 
 
import java.io.File; 
import java.io.IOException; 
import java.util.Iterator; 
import java.util.List; 
 
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.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
 
import com.bjpowernode.drp.basedata.manager.ItemManager; 
import com.bjpowernode.drp.basedata.manager.ItemManagerImpl; 
import com.bjpowernode.drp.util.ApplicationException; 
 
public class FileUploadServlet extends AbstractItemServlet { 
 private File uploadPath; 
 private File tempPath; 
   
 @Override 
 public void init() throws ServletException { 
  // Initialization occurs when the system is booted up. During initialization, check if the folder where you uploaded the images and the folder where you stored the temporary files exist. If not, create them   
   
  // Gets the actual physical path corresponding to the root directory  
  uploadPath = new File(getServletContext().getRealPath("upload")); 
  System.out.println("uploadPath=====" + uploadPath); 
  // If the directory does not exist  
  if (!uploadPath.exists()) { 
   // Create a directory  
   uploadPath.mkdir(); 
  } 
   
  // The temporary directory  
  //File tempFile = new File(item.getName()) Construct temporary objects  
  tempPath = new File(getServletContext().getRealPath("temp")); 
  if (!tempPath.exists()) { 
   tempPath.mkdir(); 
  } 
   
  // If you don't display the call to the superclass method, there won't be any itemManager Instance, thus resulting in a null pointer  
  super.init(); 
 
 } 
 
 public void doGet(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException { 
 
   doPost(request,response); 
 } 
 
  
 public void doPost(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException { 
    
  // from item_upload.jsp Take the data because the encoding format of the upload page follows 1 The difference is that enctype="multipart/form-data" 
  //form Submit the multipart/form-data, Can't use req.getParameter() To obtain data  
  //String itemNo = req.getParameter("itemNo"); 
  //System.out.println("itemNo======" + itemNo); 
    
   
 /******************************** use  FileUpload  Component parsing form ********************/ 
   
  //DiskFileItemFactory : create  FileItem  Object in which memory buffer sizes and directories for temporary files can be configured.  
  DiskFileItemFactory factory = new DiskFileItemFactory(); 
  // maximum size that will be stored in memory 
  factory.setSizeThreshold(4096); 
  // the location for saving data that is larger than getSizeThreshold() 
  factory.setRepository(tempPath); 
     
  //ServletFileUpload : Responsible for processing the uploaded file data and encapsulating the data of each part 1 to  FileItem  In the object.  
  // When the uploaded file data is received, the contents are saved to the in-memory cache if the file content exceeds  DiskFileItemFactory  The size of the buffer specified,  
  // Then the file will be saved to disk and stored as  DiskFileItemFactory  Specifies temporary files in the directory.  
  // After receiving all the file data, ServletUpload Then write the data from the file to the file under the upload file directory  
    
  ServletFileUpload upload = new ServletFileUpload(factory); 
  // maximum size before a FileUploadException will be thrown 
  upload.setSizeMax(1000000 * 20); 
   
   
  /********** Parse the data passed from the form and return List A collection of data - type :FileItem***********/ 
   
  try { 
    
   List fileItems = upload.parseRequest(request); 
    
   String itemNo = ""; 
   //Iterator iter = fileItems.iterator() Take its iterator  
   //iter.hasNext() Check to see if there are any elements left in the sequence  
   for (Iterator iter = fileItems.iterator(); iter.hasNext();) { 
    // Get the bottom of the sequence 1 An element  
    FileItem item = (FileItem) iter.next(); 
 
    // Determines whether it is a file or text message  
    // Is a normal form input field  
    if(item.isFormField()) { 
     if ("itemNo".equals(item.getFieldName())) { 
      itemNo = item.getString(); 
     } 
    } 
    // Whether it is input="type" The input field  
    if (!item.isFormField()) {     
     // The name and full path of the uploaded file  
     String fileName = item.getName(); 
      
     long size = item.getSize(); 
     // Determine if the file was selected  
     if ((fileName == null || fileName.equals("")) && size == 0) { 
      continue; 
     } 
     // Truncated string   Such as: C:\WINDOWS\Debug\PASSWD.LOG 
     fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); 
      
      //  Save the file on the server's physical disk: 1 The parameter is: full path (not including file name) 2 The parameters are: file name   
     //item.write(file); 
     // Modify file name and material name 1 To, and forced modification of the file extension gif 
     //item.write(new File(uploadPath, itemNo + ".gif")); 
     // Save the file to a directory without changing the file name  
     item.write(new File(uploadPath, fileName)); 
      
      
      
     // Write the image file name to the database      
     itemManager.uploadItemImage(itemNo, fileName); 
      
    } 
   } 
   response.sendRedirect(request.getContextPath() + "/servlet/item/SearchItemServlet"); 
  } catch (Exception e) { 
   e.printStackTrace(); 
   throw new ApplicationException(" Upload failed! "); 
  }  
   
   
 } 
  
 
} 

This class inherits AbstractItemServlet: the abstract parent of all materials Servlet and is responsible for instantiating ItemManager


/** 
 *  All materials Servlet Abstract parent class, responsible for instantiation ItemManager 
 * @author LiMin 
 * 
 */ 
public abstract class AbstractItemServlet extends HttpServlet { 
 
 // It's not thread safe, but if it's read-only, you won't get an error  
 protected ItemManager itemManager = null; 
   
 @Override 
 public void init() throws ServletException { 
  itemManager = new ItemManagerImpl() 
 } 
  
 
} 

ItemManagerImpl is a subclass that implements the ItemManager interface. There is one problem with this design mode, which is the optimization of remuneration. But here, in order to illustrate the picture uploading, there is no unnecessary elaboration.

Conclusion:

About the initialization method of init() :
When Servlet is initialized, the directory is created dynamically. Here, 1 upload and temporary file tempPath are created into the project directory under webapps of tomcat.
It's worth noting that you need to show the call to the super.init () method (super is not a reference to the parent object, but is responsible for the call to the parent method), otherwise you might end up with a null pointer to the class.
Uploading is done in three steps: parse the form using the FileUpload component; Parse the data passed by the form and return List collection data - type :FileItem; Finally upload the picture.
Use the isFormField() method of FileItem to determine whether it is plain text or a file;
Use FileItem.write (new File(uploadPath, fileName)) to upload the file, the first parameter is: full path (not including file name), the second parameter is: file name; the second parameter is: file name; the third parameter is: file name.

Working with plain text data:


 if ("itemNo".equals(item.getFieldName())) {
itemNo = item.getString();
 } 


Uploading is a mature technology for many years, many of which have been packaged and can be directly used in our daily projects, but it is essential to understand some basic principles.


Related articles: