[JAVA] About image upload of jsp (servlet)

Installation of upload button in POST Servlet

Upload.java


package pakage;

@WebServlet("/upload")
@MultipartConfig(location="/tmp",maxFileSize=1048576)
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
      @Override

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Create a variable called part
		Part part = request.getPart("file");
        //part(Mainly jsp)Get the file name sent from
		String name = this.getFileName(part);

		part.write(getServletContext().getRealPath("/WEB-INF/lib/upload")+ "/" + name);
		response.sendRedirect("jsp/upload.jsp");
	}
      private String getFileName(Part part){
          String name = null;
          for(String dispotion : part.getHeader("Content-Disposition").split(";")){
              if(dispotion.trim().startsWith("filename")){
                  name = dispotion.substring(dispotion.indexOf("=") + 1).replace("\"","").trim();
                  name = name.substring(name.lastIndexOf("\\") + 1 );
                  break;
              }
          }
          return name;
    }
}

CreateServlet.java


package controllers;


@WebServlet("/create")
public class CreateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String _token = (String)request.getParameter("_token");
		if(_token != null && _token.equals(request.getSession().getId())){
		    EntityManager em = DBUtil.createEntityManager();

		    Reshipi r = new Reshipi();

		    String name = request.getParameter("name");
		    r.setName(name);

		    String content = request.getParameter("content");
		    r.setContent(content);

		    Timestamp currentTime = new Timestamp(System.currentTimeMillis());
		    r.setCreated_at(currentTime);
		    r.setUpdated_at(currentTime);

		    em.getTransaction().begin();
		    em.persist(r);
		    em.getTransaction().commit();
		    em.close();

		    response.sendRedirect(request.getContextPath() + "/index");

		}
	}
}

When combining the two

package controllers;

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

    public CreateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String _token = (String)request.getParameter("_token");
		if(_token != null && _token.equals(request.getSession().getId())){
		    EntityManager em = DBUtil.createEntityManager();

		    Reshipi r = new Reshipi();

		    String name = request.getParameter("name");
		    r.setName(name);

		    String content = request.getParameter("content");
		    r.setContent(content);


		    Part part = request.getPart("file");
		    String filename = this.getFileName(part);

		    Timestamp currentTime = new Timestamp(System.currentTimeMillis());
		    r.setCreated_at(currentTime);
		    r.setUpdated_at(currentTime);

		    em.getTransaction().begin();
		    em.persist(r);
		    em.getTransaction().commit();
		    em.close();

		    response.sendRedirect(request.getContextPath() + "/index");
		}
	}
    private String getFileName(Part part){
        String filename = null;
        for(String dispotion : part.getHeader("Content-Disposition").split(";")){
            if(dispotion.trim().startsWith("filename")){
                filename = dispotion.substring(dispotion.indexOf("=") + 1).replace("\"", "").trim();
                filename = filename.substring(filename.lastIndexOf("\\") + 1);
                break;
            }
        }
        return filename;
    }
}

Private String getFileName (Part part) Always write the method outside the POST method, not inside it. Put what was in the POST method into the POST method, and what was in the GET method into the GET method.

Recommended Posts

About image upload of jsp (servlet)
About [servlet] [JSP] [tomcat]
Image upload
About the version of Docker's Node.js image
Simultaneous upload of image saving and linking
Think about the combination of Servlet and Ajax
About disconnect () of HttpURLConnection
About selection of OpenJDK
About DI of Spring ②
About form. ○○ of form_with
About @Accessors of Lombok
About the handling of Null
[Java] Beginner's understanding of Servlet-②
About simple operation of Docker
About the description of Docker-compose.yml
[Java] Beginner's understanding of Servlet-①
Implementation of image preview function
About size comparison of compareTo
About types of code coverage
Java Servlet / JSP View drawing
Getting Started with JSP & Servlet
JSP error display from Servlet
Memorandum of understanding about LOD.
About partial match of selector