In general, there are two ways to upload images. One is to write the image file into the database, and the other is to store it in the server file directory. The image files written to the database need to be converted into a binary stream format, occupying database space, and are suitable for storage of a small number of images. For example, some small icons in the system have the advantage of writing to the database that they are relatively safe and are not easily deleted by users accidentally.
If you store a large number of images, it is usually done to save them to a folder on the server. There are many ways to complete upload, you can use the streaming method and the ftp method, and the fileupload method is used here.
With different system sizes, the processing methods of image files are also different. If the number of pictures in the system is not large, just store all the pictures in the same directory. If the pictures are accumulated more, you can classify and store the pictures according to the material classification, which will save some time in searching files on disk.
When uploading pictures to files, you can upload pictures directly to the directory, you can also write the image file name and file path to the database, or you can dynamically create file paths in the program. If the company requires images to be stored on a special server, it is more appropriate to write the file path to the full file. Generally, it is easier to process if a material (material) corresponds to a picture. If it corresponds to multiple pictures, it needs to be used in conjunction with recycle. On the one hand, it is necessary to process the dynamic display of the picture, and on the other hand, it is necessary to check whether the naming of the picture file is duplicated. In addition, when processing images (uploading, deleting, and modifying), you need to cooperate with transactions.
The following is a key introduction to the most basic implementation of using fileupload to achieve image upload.
1. Use file tags on the front end:
<input name = "fileName" type ="file" class ="text1" size ="40" maxlength="40">
2. Set the enctype format of the file: multipart/form-data
<form name="itemForm" target="_self" id="itemForm" method="post" action="servlet/item/FileUploadServlet" enctype="multipart/form-data" >
Instructions about enctype="multipart/form-data":
If this format is used in jsp, the corresponding Servlet cannot use request.getParameter() to obtain parameters. You must use the parseRequest method of the ServletFileUpload object to first parse the data in the request object, and then use the isFormField flag of the parsed element and cooperate with the getFieldName method to obtain the data.
3. Implementation 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.baseddata.manager.ItemManager; import com.bjpowernode.drp.baseddata.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 { // When the system starts, start initialization. During initialization, check whether the folder where the picture is uploaded and the folder where the temporary files are stored exists. If it does not exist, create //Get the real 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 the directory uploadPath.mkdir(); } //Temporary directory//File tempFile = new File(item.getName()) Construct the temporary object tempPath = new File(getServletContext().getRealPath("temp")); if (!tempPath.exists()) { tempPath.mkdir(); } //If the parent class method is not displayed, there will be no itemManager instance, which will cause 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 { //Get data from item_upload.jsp, because the encoding format of the uploaded page is different from the general one, using enctype="multipart/form-data" //Form submission uses multipart/form-data, and data cannot be obtained using req.getParameter() //String itemNo = req.getParameter("itemNo"); //System.out.println("itemNo=======" + itemNo); /*********************************************Use the FileUpload component to parse the form*************************/ //DiskFileItemFactory: Create a factory for FileItem object. In this factory class, you can configure the memory buffer size and the directory where temporary files are stored. 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 uploaded file data and encapsulating each part of the data into a FileItem object. //When receiving uploaded file data, the content will be saved to the memory cache. If the file content exceeds the size of the buffer specified by DiskFileItemFactory, //The file will be saved to disk and stored as a temporary file in the specified directory of DiskFileItemFactory. //After the file data is received, ServletUpload writes the data from the file into the file in the uploaded file directory ServletFileUpload upload = new ServletFileUpload(factory); // maximum size before a FileUploadException will be thrown upload.setSizeMax(1000000 * 20); /******************* parse the data passed by the form and return the List collection data-type: FileItem***************/ try { List fileItems = upload.parseRequest(request); String itemNo = ""; //Iterator iter = fileItems.iterator() Take its iterator //iter.hasNext() Check whether there are elements in the sequence for (Iterator iter = fileItems.iterator(); iter.hasNext();) { //Get the next element in the sequence FileItem item = (FileItem) iter.next(); //Judge whether it is file or text information //It is an ordinary form input field if(item.isFormField()) { if ("itemNo".equals(item.getFieldName())) { itemNo = item.getString(); } } //Is it input field if (!item.isFormField()) { //The name and full path of the uploaded file String fileName = item.getName(); long size = item.getSize(); //Determine whether the file is selected if ((fileName == null || fileName.equals("")) && size == 0) { continue; } //Intercept the 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: the first parameter is: the full path (excluding the file name). The second parameter is: file name //item.write(file); //Modify the file name and the material name are the same, and the file extension is forced to be gif //item.write(new File(uploadPath, itemNo + ".gif")); //Save the file to the directory without modifying 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 the AbstractItemServlet: The abstract parent class of all material Servlets, responsible for instantiating the ItemManager
/** * The abstract parent class of all material Servlets is responsible for instantiating ItemManager * @author LiMin * */ public abstract class AbstractItemServlet extends HttpServlet { //Although it is not thread-safe, if it is read-only, there will be no errors 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 model, which has salary optimization, but here we will not make any irrelevant remarks to explain the upload of pictures.
Summarize:
About the init() initialization method:
When Servlet is initialized, the directory is created dynamically. Here is a upload and temporary file tempPath to the project and directory under tomcat's webapps.
It is worth noting that the super.init() method needs to be called here (super is not a reference to the parent class object, but is responsible for the call to the parent class method), otherwise, it may cause a null pointer to the class.
Uploading is roughly performed in three steps: use the FileUpload component to parse the form; parse the data passed by the form, and return the List collection data-type: FileItem; finally upload the image.
Use FileItem's isFormField() method to determine whether it is a normal text or a file;
Use FileItem.write(new File(uploadPath, fileName)) to upload the file. The first parameter is: the full path (excluding the file name). The second parameter is: the file name;
Processing normal text data:
if ("itemNo".equals(item.getFieldName())) {itemNo = item.getString(); }Uploading is a relatively mature technology for many years, and there are many packaged ones that we can use directly in our daily projects, but understanding some basic principles is essential.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.