JAVA realizes page uploading pictures or files

Note: I didn't plan to write this blog, because there are too many blogs about uploading images/files on the page. But I found that those blogs are almost the same, this is not the key, the key is that the code is wrong, and the mistakes are all the same, this is a bit too much, so I wrote this blog to let more people and less trouble to find bugs, Also let me keep a file for myself.
Two packages are needed here:
Friends who don't have it can go to download: (Because the download is very simple, I won't teach you one by one here, just click the link below)

I will post the code below, you should be able to run it after copying and changing the package name.
In order to reduce the amount of code, here I have extracted a few important notes that I wrote.
Regarding the place where the file is named, I think it is better to put it directly in the code and not write it out.  

//When Baidu arrived, there is no code on the right, but without this code, the program will report an error //savePath = savePath.replace("\\", "\\\\");
 //The file path obtained automatically above It is divided by \, but obviously if you write a string like this, aa\bb\dasd will compile errors.//We
 just need to escape, but why is \\ escaped into \\\\? You can go to print System.out.println("\\"); output \

//How many blogs in this place are written like this if(!file.exists() && file.isDirectory()){ }
//I really doubt that those who copy blogs did not run the code and just copied it.
//file.isDirectory() API description is: Test whether the file represented by this abstract pathname is a directory.
//You think there are only two normal cases, one is that we have created such a directory. Of course this is fine.
//There is also a case that we did not create this directory, we need the following file.mkdir() method to automatically create
//In this case, there is no directory. Then this method returns false, so of course this method of creating a directory will not be executed. There is no directory, copy the following to this directory, there is no doubt that an error will be reported

Code of UploadServlet.java:

package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

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;

public class UploadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");	
		savePath = savePath.replace("\\", "\\\\");
		File file = new File(savePath);
		/ / Determine whether the save directory of the uploaded file exists
		if(!file.exists()){
			//The directory does not exist and needs to be created
			file.mkdir();
		}
		//upload prompt message
		String message="";	
		try{
			//Use the apache file upload component to handle the file upload step
			//1. Create a DiskFileItemFactory factory
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//2, create a file upload parser
			ServletFileUpload upload = new ServletFileUpload(factory);
			//Solve the Chinese garbled character of the uploaded file name
			upload.setHeaderEncoding("UTF-8");
			//3. Determine whether the submitted data is the data of the upload form
			if(!ServletFileUpload.isMultipartContent(request)) {
				// Get the data in the traditional way
//				request.getParameter(arg0);
				
				return ;
			}
			//4. Use the ServletFileUpload parser to upload data, and the parsing result returns a List<FileItem> collection
			// Each FileItem corresponds to an input item of a Form form
			List<FileItem> list = upload.parseRequest(request);
			for(FileItem item : list) {
				//If the fileitem encapsulates the data of ordinary input items such as text password ...
				if(item.isFormField()) {
					String name = item.getFieldName();
					/ / Solve the Chinese garbled problem of the data of ordinary input items
					String value = item.getString("UTF-8");
					System.out.println(name +"=" + value);
				}else { //If the uploaded file is encapsulated in fileitem
					String filename = item.getName();
					System.out.println(filename);
					if(filename == null || filename.trim().equals("")){
						continue;
					}
					//Note: The file names submitted by different browsers are different. Some browsers submit file names with paths, such as: c:\a\b\1.txt, while others are just simple file names. , such as: 1.txt
				
					//You can choose one of the following two file names
// --------------------------------The first type (same as the uploaded file name)----- ---------------------------------------
					/ / Process the obtained path part of the file name of the uploaded file, and only keep the file name part
//					filename = filename.substring(filename.lastIndexOf("\\")+1);
					
//----------------------The second type (the custom file name I use here is UUID, mainly to get the extension name of the source file)- ---------------------
					//Get the extension of the image
					filename = filename.substring(filename.lastIndexOf(".")+1);
					// Give the file a new name UUID
					filename = UUID.randomUUID().toString()+"."+filename;
					
					
					//Get the input stream of the uploaded file in the item
					InputStream in = item.getInputStream();
					//Create a file output stream
					FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
					//create a buffer
					byte[] buffer = new byte[1024];
					//Identifies whether the data in the input stream has been read or not
					int len ​​= 0;
					//The loop reads the input stream into the buffer,
					while((len = in.read(buffer)) > 0) {
						//Use the FileOutputStream input stream to write the buffer data to the specified directory (savePath + "\\" +filename)
						out.write(buffer,0,len);
					}
					//close the stream
					in.close();
					out.close();
					//Delete the temporary file generated when processing the file upload
					item.delete();
					message = "File upload successful!!!";					
				}
			}			
		} catch(Exception e) {
			message = "File upload failed!!!";
			e.printStackTrace ();
		} finally {
			request.setAttribute("message", message);
			request.getRequestDispatcher("/message.jsp").forward(request, response);
		}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

The code of web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>unploadanddownload</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>servlet.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>
</web-app>

code of message.jsp

 
 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message prompt</title>
</head>
<body>
	${message}
</body>
</html>

code of upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File upload</title>
</head>
<body>
	<form action="${pageContext.request.contextPath}/UploadServlet"
	enctype="multipart/form-data" method="post">
		上传用户:<input type="text" name="username"> <br/>
		上传文件1:<input type="file" name="file1"> <br/>
		上传文件2:<input type="file" name="file2"> <br/>
		<input type="submit" value="提交">
	
	</form>
</body>
</html>




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325819072&siteId=291194637