catalogue
3. The code is as follows (including comments)
3.1 obtain DiskFileItemFactory object
1. Brief introduction
In a web project, it is very common for users to upload files to the project, such as avatar setting, background picture setting and so on. When saving the files uploaded by users, the server needs to solve the following four problems: 1 The files uploaded by the user cannot be accessed directly by entering the url in the address bar; 2. Files uploaded by users cannot be overwritten (files with the same name in the same folder will be overwritten).
This article will briefly explain how to upload files in Java Web projects and solve the four problems mentioned above
2. Principle explanation
The form of uploading files is shown in the figure
Generally, when processing the uploaded files, we use the stream to process them, but in this case, we need to implement the bottom layer of network communication by ourselves, which is too troublesome. Here, we use the Commons IO component of apache to complete it.
The ServletFileUpload class is responsible for processing the uploaded file data and encapsulating each input item in the form into a FileItem object. When obtaining the ServletFileUpload object, a DiskFileItemFactory object is required
After obtaining the FileItem object through the ServletFileUpload object, traverse all FileItem objects to determine whether each object is just a simple form element or contains a file. If it contains a file, process and save the file and forward it to the page of uploading information.
3. The code is as follows (including comments)
3.1 obtain DiskFileItemFactory object
public DiskFileItemFactory getDiskFileItemFactory(File tempFile){ DiskFileItemFactory factory = new DiskFileItemFactory(); // Set a size limit for the uploaded file. When the file exceeds this size, it will be cached in the temporary storage area factory.setSizeThreshold(1024*1024); //The size is 1M factory.setRepository(tempFile); //Set staging area return factory; }
3.2 get ServletFileUpload object
public ServletFileUpload getServletFileUpload(DiskFileItemFactory factory){ ServletFileUpload upload = new ServletFileUpload(factory); upload.setProgressListener(new ProgressListener() { @Override // pBytesRead: the size of the file that has been read // pContentLength: total file size public void update(long pBytesRead, long pContentLength, int pItems) { System.out.println("Total size:"+ pContentLength + ";Uploaded:" + pBytesRead); } }); // Dealing with garbled code upload.setHeaderEncoding("UTF-8"); // Sets the maximum value for a single file upload.setFileSizeMax(1024*1024*10); // Set the total size of files that can be uploaded upload.setSizeMax(1024*1024*10); return upload; }
3.3 uploading files
public void uploadFile(HttpServletRequest req, HttpServletResponse resp,ServletFileUpload upload, String uploadPath) throws IOException, ServletException { String msg = "File upload failed"; // Parse the front-end request, encapsulate it into a FileItem object, and get it from the ServletFIleUpload object List<FileItem> fileItems = null; try { fileItems = upload.parseRequest(req); } catch (FileUploadException e) { e.printStackTrace(); } for (FileItem fileItem : fileItems) { // The current FileItem object is just a form object if(fileItem.isFormField()){ String name = fileItem.getFieldName(); //Get the name value of the form control String value = fileItem.getString("UTF-8");//Get text and deal with garbled code System.out.println(name+" :"+value); }else { // The current FileItem contains files // ===========================Processing files=============================== String uploadFileName = fileItem.getName(); if(uploadFileName.trim().equals("") || uploadFileName==null){ continue; } // Get the uploaded file name String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/")+1); // Get uploaded file suffix String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".")+1); // Use UUID to obtain a unique universal identification code to ensure that the file name is unique // Everything in network transmission needs to be serialized // If the entity class wants to run on multiple computers, it needs to be transferred = = = "use the serial number String uuidPath = UUID.randomUUID().toString(); // ==========================Storage address========================================== String readPath = uploadPath+"/"+uuidPath; // Create a folder for each file File realPathFile = new File(readPath); if(!realPathFile.exists()){ realPathFile.mkdir(); } // ===========================File transfer========================================== // Get the stream of file upload InputStream inputStream = fileItem.getInputStream(); // Create a file output stream FileOutputStream fos = new FileOutputStream(readPath+"/"+fileName); // Create a buffer byte[] buffer = new byte[1024*1024]; // Judge whether the reading is completed int len = 0; while ((len=inputStream.read(buffer))>0){ fos.write(buffer, 0, len); } // Close flow fos.close(); inputStream.close(); } msg = "File uploaded successfully"; } req.setAttribute("msg", msg); req.getRequestDispatcher("info.jsp").forward(req, resp); }
3.4 doPost()
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Determine whether the uploaded file is an ordinary form or a form with files String msg = "File upload failed"; if(!ServletFileUpload.isMultipartContent(req)){ return; } // Create a save path for the uploaded file. It is recommended to put it under the web inf path to ensure security. Users cannot directly access the uploaded file String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); File uploadFile = new File(uploadPath); if(!uploadFile.exists()){//If the folder does not exist, create a modified folder uploadFile.mkdir(); } // Cache temporary files // Temporary path. If the file exceeds the expected size, put it under the temporary folder String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp"); File tmpFile = new File(tmpPath); if(!tmpFile.exists()){ tmpFile.mkdir(); } // To process the uploaded files, you generally need to obtain them through streaming // Here, the components of apache are used to implement commons io /* * ServletFileUpload It is responsible for processing the uploaded file data and encapsulating each input item in the form into a fileItem object * The DIskFileItemFactory object is required when parsing the request using the ServletFileUpload object * For all, the DiskFileItemFactory object needs to be constructed before parsing*/ // 1. Create DiskFileIntemFactory object to handle file upload path or size limit DiskFileItemFactory factory = getDiskFileItemFactory(tmpFile); // 2. Get ServletFileUpload ServletFileUpload upload = getServletFileUpload(factory); // 3. Process uploaded files uploadFile(req, resp,upload, uploadPath); }
Add: when uploading a file through a form, the get method has restrictions on the size of the uploaded file, and the post method has no restrictions, so the post method is generally used. Moreover, if the get method is used, an error will occur when obtaining ServletFileUpload. In addition, if the form contains a file upload input, the enctype attribute of the form must be set to multipart / form data.
4. Operation results
After submitting the files through the form, you can find the project folder in the tomcat directory. There are two more folders, upload and temp, in the WEB-INF directory. The uploaded files are saved under these two folders.