1

I have servlet that store image after user pick it

public class HelloServlet extends HttpServlet {
  private String uploadDir = "userProfileImages";
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("application/json");
        String uploadPath = Utils.getFolderStoreImage(getServletContext().getRealPath(File.separator),uploadDir);
        String fileName;
        String extension;
        ObjectMapper mapper = new ObjectMapper();
       File uploadDir = new File(uploadPath);
       if (!uploadDir.exists()) {
          uploadDir.mkdir();
        }
           Part part = request.getPart("file");
           fileName = part.getSubmittedFileName();
           
           part.write(uploadPath + File.separator + fileName);
            String message = "Your image has been successfully loaded";
           response.getWriter().write(mapper.writeValueAsString(message));
    }
}

Class that gets folder to store images

   public class Utils {
        public static String getFolderStoreImage(String webContentRoot,String dir) {
            if (webContentRoot.endsWith("\\")) {
                webContentRoot = webContentRoot.substring(0, webContentRoot.length() - 1);
            }
            String folder = webContentRoot.substring(0, webContentRoot.lastIndexOf(File.separator) + 1) + dir +File.separator;
            return folder;
        }
    }

Now my index jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<img src="userProfileImages/Lifan.jpg" />
</body>
</html>

File is uploaded in target dir(I don't know Is It good )

enter image description here

How can i get correct src to that images?Should I store images in that dir(target)?If not what is better way to do?

0 Answers0