Java implements image upload to server and reads the uploaded image

Keywords: Session SQL MySQL Java

Many websites can upload avatars, you can choose your favorite pictures as avatars, upload from the local, the next time you log in, you can directly display the uploaded avatars, so how to achieve this?

 

Here's my implementation process (just personal implementation ideas, how the actual website is not clear)

Ideas for realization:

Tools: MySQL, eclipse

First, two tables, a t_user table, are created in MySQL to store personal information such as username, password, etc.

A t_touxiang table is used to store the uploaded image's storage path in the server, as well as the image name and user ID.

The user ID in the T_touxiang table corresponds to the ID in t_user.

t_user table SQL:

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;

T_touxiang table SQL:

DROP TABLE IF EXISTS `t_touxiang`;
CREATE TABLE `t_touxiang` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `image_path` varchar(255) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  `old_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `img_user` (`user_id`),
  CONSTRAINT `img_user` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

First, write an Upload Servlet. java to handle the upload of image files, and store the information of image path, image name and so on into the t_touxiang data table. The code is as follows:

@WebServlet("/UploadServlet.do")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	// Determine whether the uploaded form is multipart/form-data type
	HttpSession session = request.getSession();
	User user = (User) session.getAttribute("user"); // Put the User object into the session at login time
							 // in

	if (ServletFileUpload.isMultipartContent(request)) {

	    try {
		// 1. Create DiskFileItemFactory object, set buffer size and temporary file directory
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// System.out.println(System.getProperty("java.io.tmpdir"); //Default temporary folder

		// 2. Create the ServletFileUpload object and set the size limit of the uploaded file.
		ServletFileUpload sfu = new ServletFileUpload(factory);
		sfu.setSizeMax(10 * 1024 * 1024);// No more than 10M 1024 byte in byte units=
						 // 1kb 1024kb=1M 1024M = 1G
		sfu.setHeaderEncoding("utf-8");

		// 3.
		// Call the ServletFileUpload.parseRequest method to parse the request object and get a List object that holds all the uploaded content.
		@SuppressWarnings("unchecked")
		List<FileItem> fileItemList = sfu.parseRequest(request);
		Iterator<FileItem> fileItems = fileItemList.iterator();

		// 4. Traverse through the list, each iteration of a FileItem object, calling its isFormField method to determine whether it is uploaded files?
		while (fileItems.hasNext()) {
		    FileItem fileItem = fileItems.next();
		    // Common form elements
		    if (fileItem.isFormField()) {
			String name = fileItem.getFieldName();// name attribute value
			String value = fileItem.getString("utf-8");// Value value corresponding to name

			System.out.println(name + " = " + value);
		    }
		    // Elements of uploaded files for <input type="file">
		    else {
			String fileName = fileItem.getName();// File name
			System.out.println("Original file name:" + fileName);// Koala.jpg

			String suffix = fileName.substring(fileName.lastIndexOf('.'));
			System.out.println("Extension:" + suffix);// .jpg

			// New file name (unique)
			String newFileName = new Date().getTime() + suffix;
			System.out.println("New file name:" + newFileName);// image\1478509873038.jpg

			// 5. Call FileItem's write() method to write to the file
			File file = new File("D:/lindaProjects/mySpace/wendao/WebContent/touxiang/" + newFileName);
			System.out.println(file.getAbsolutePath());
			fileItem.write(file);

			// 6. Call FileItem's delete() method to delete temporary files
			fileItem.delete();

			/*
			 * Note 1. Save the name of the source file Koala.jpg 2. Save the relative path
			 * image/1478509873038.jpg
			 * 
			 */
			if (user != null) {
			    int myid = user.getId();
			    String SQL = "INSERT INTO t_touxiang(image_path,user_id,old_name)VALUES(?,?,?)";
			    int rows = JdbcHelper.insert(SQL, false, "touxiang/" + newFileName, myid, fileName);
			    if (rows > 0) {
				session.setAttribute("image_name", fileName);
				session.setAttribute("image_path", "touxiang/" + newFileName);
				response.sendRedirect(request.getContextPath() + "/upImage.html");
			    } else {

			    }

			} else {
			    session.setAttribute("loginFail", "Please login");
			    response.sendRedirect(request.getContextPath() + "/login.html");
			}

		    }
		}

	    } catch (FileUploadException e) {
		e.printStackTrace();
	    } catch (Exception e) {
		e.printStackTrace();
	    }

	}
    }
}

While uploading and writing pictures to the database, the path of pictures is sent to HTML interface by session.

 

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Replace the avatar </title>

</head>

<body>

         <formaction="UploadServlet.do" method="post"enctype="multipart/form-data">

Local directory: <inputtype="file" name="uploadFile">

           <img src="${image_path}" width="200" height="200">

Inputtype= "submit" value= "upload avatar"/>

   </form>

</body>

</html>

So far, image upload database and local server have been implemented, so how to display personal information and uploaded avatars in HTML interface?

 

First, a PersonServlet class is defined to read the contents of the database and send it to the HTML interface.

The code is as follows:

@WebServlet("/persons.do")
public class PersonServlet extends HttpServlet {

    private static final long serialVersionUID = -800352785988546254L;

    protected void service(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	// Determine whether the uploaded form is multipart/form-data type
	Touxiang tx=null;
	
	HttpSession session = request.getSession();
	User user = (User) session.getAttribute("user"); // Put the User object into the session at login time
	if(user!=null){
	    int myid=user.getId();
	    String SQL="SELECT id,image_path,old_name FROM t_touxiang WHERE user_id=?";
	    ResultSet rs=JdbcHelper.query(SQL,myid);
	    String uSQL="SELECT username,password FROM t_user WHERE id=?";
	    ResultSet urs=JdbcHelper.query(uSQL,myid);
	    System.out.println( "My personal id yes: " + myid);
	    final List<Touxiang> touxiang=new ArrayList<>();
	    try {
		if(rs.next())
		{
		    tx=new Touxiang();
		    tx.setId(rs.getInt(1));
		    tx.setImage_path(rs.getString(2));
		    tx.setOld_name(rs.getString(3));
		    touxiang.add(tx);
		}
		if(urs.next()){
		    user.setUsername(urs.getString(1));
		    user.setPassword(urs.getString(2));
		    user.setTouxiang(touxiang);
		}
		
	    } catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	   
		session.setAttribute("user", user);
		System.out.println( "My id: " + myid);
		response.sendRedirect( request.getContextPath() + "/person.html");
	}
    }
}

The HTML interface receives information and displays it. The code is as follows:

	<div>
	<form action="UploadServlet.do" method="post" enctype="multipart/form-data">
      		 <div><a href="$path/upImage.html">Change the Avatar</a></div>
        	
        	#foreach( $ut in  $user.getTouxiang() )
        	 <img src=" $ut.getImage_path()"  width="200" height="200">
        	 #end
        	 <div>My avatar:</div>
        	 <div>My name: $user.getUsername()</div>
        	 <div><a href="$path/myAnswer.do">My answer</a></div>
		<div><a href="$path/myQuestion.do">My questions</a></div>
   	 </form>
	</div>

So far, a Java-based image upload server, path stored in MySQL, and read out in the HTML interface function is basically realized. Some plug-ins can be selected to complete the processing before uploading the avatar. Here is just a simple implementation of the basic functions.

Posted by Dustin013 on Sun, 07 Apr 2019 18:42:30 -0700