Implementing Avatar Upload with Java, MySQL, and Servlet

Implementing Avatar Upload with Java, MySQL, and Servlet

In this article, we will explore the process of uploading avatars to a server using Java, MySQL, and Servlet. We will cover the creation of two tables in MySQL, the implementation of an upload servlet, and the display of uploaded images in an HTML interface.

Database Schema

To store user information and uploaded images, we need to create two tables in MySQL. The t_user table will store user names, passwords, and other personal information, while the t_touxiang table will store the uploaded images along with their corresponding user IDs.

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;

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;

Upload Servlet

The UploadServlet class is responsible for processing uploaded image files and storing their paths in the t_touxiang table. The servlet uses the ServletFileUpload class to parse the multipart/form-data request and extract the uploaded file.

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

  protected void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");

    if (ServletFileUpload.isMultipartContent(request)) {
      try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        sfu.setSizeMax(10 * 1024 * 1024);
        sfu.setHeaderEncoding("utf-8");

        List<FileItem> fileItemList = sfu.parseRequest(request);
        Iterator<FileItem> fileItems = fileItemList.iterator();

        while (fileItems.hasNext()) {
          FileItem fileItem = fileItems.next();

          if (fileItem.isFormField()) {
            String name = fileItem.getFieldName();
            String value = fileItem.getString("utf-8");
            System.out.println(name + "=" + value);
          } else {
            String fileName = fileItem.getName();
            System.out.println("Original File Name:" + fileName);
            String suffix = fileName.substring(fileName.lastIndexOf('.'));
            System.out.println("Extension:" + suffix);
            String newFileName = new Date().getTime() + suffix;
            System.out.println("New file name:" + newFileName);

            File file = new File("D:/lindaProjects/mySpace/wendao/WebContent/touxiang/" + newFileName);
            System.out.println(file.getAbsolutePath());
            fileItem.write(file);
            fileItem.delete();

            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 {
                session.setAttribute("loginFail", "log in");
                response.sendRedirect(request.getContextPath() + "/login.html");
              }
            } else {
              session.setAttribute("loginFail", "log in");
              response.sendRedirect(request.getContextPath() + "/login.html");
            }
          }
        }
      } catch (FileUploadException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}

Displaying Uploaded Images

To display the uploaded images in an HTML interface, we need to create a servlet that retrieves the user’s image path and name from the database and displays them in the interface.

@WebServlet("/persons.do")
public class PersonServlet extends HttpServlet {
  private static final long serialVersionUID = -800352785988546254L;

  protected void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");

    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 is:" + myid);

      List<Touxiang> touxiang = new ArrayList<>();
      try {
        if (rs.next()) {
          Touxiang 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) {
        e.printStackTrace();
      }

      session.setAttribute("user", user);
      System.out.println("My id:" + myid);
      response.sendRedirect(request.getContextPath() + "/person.html");
    }
  }
}

HTML Interface

The HTML interface will display the user’s uploaded images and provide a link to replace the avatar.

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

This implementation provides a basic understanding of how to upload avatars to a server using Java, MySQL, and Servlet. However, there are many ways to improve this implementation, such as using a framework like Spring to simplify the development process, adding more features to the HTML interface, and implementing security measures to prevent unauthorized access to the uploaded images.