0

I can’t manage to find an appropriate answer to this question for 3 days now. I am building a web app in Java. In my front end in jsp i have a form that gets an avatar picture from the user. I save this picture in my servlet in a local directory on the disk and i also save the path of the picture in my postgres database. After registering the user i redirect him to a profile page where i want to see the picture from the path stored in my postgres db of that particular picture. I get an error that I cannot load resources from local drive. From my searches I understand this is a security feature, but what is the best practice in this case ? I also understand that storing images in database as blobs is not the best practice. I also read something about the fact that i should somehow save these pictures in my tomcat but i can`t manage to figure out where exactly and how. Below is my code for servlet:

   @MultipartConfig(fileSizeThreshold = 1024 * 1024,
    maxFileSize = 1024 * 1024 * 10,
    maxRequestSize = 1024 * 1024 * 100)
    
    @WebServlet(urlPatterns = {"/signup"})
    public class SignUpServlet extends HttpServlet {
        private final String SAVE_DIR = "C:\\Users\\john\\Google Drive\\AvatarPic\\";
        private UserDBManagement userDBManagement;
    
        @Override
        public void init() throws ServletException {
            this.userDBManagement = UserDBManagement.getInstance();
        }
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.getRequestDispatcher("JSPS/signup.jsp").forward(req, resp);
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            //Get parts from form fields
            String firstName = manageInput(req.getPart("firstName"));
            String lastName = manageInput(req.getPart("lastName"));
            String address = manageInput(req.getPart("address"));
            String country = manageInput(req.getPart("country"));
            String emailOne = manageInput(req.getPart("emailOne"));
            String emailTwo = manageInput(req.getPart("emailTwo"));
            String passwordOne = manageInput(req.getPart("passwordOne"));
            String passwordTwo = manageInput(req.getPart("passwordTwo"));
            String date = manageInput(req.getPart("date"));
            String gender = manageInput(req.getPart("gender"));
            switch (gender){
                case "1": gender = "male";
                break;
                case "2": gender = "female";
                break;
                case "3": gender = "non-disclosure";
                break;
            }
            String userName = manageInput(req.getPart("username"));
            Part avatarPart = req.getPart("avatar");
    
            //Save the avatar to disk
            String fileName = avatarPart.getSubmittedFileName();
            for(Part part: req.getParts()){
                part.write(SAVE_DIR + fileName);
            }
    
            //Saving avatar name as string
            String avatar = SAVE_DIR + fileName;
    
    
    
            //adding new registered user to database and logging him up
            User newUser = new User(firstName, lastName, address, country, emailOne, passwordOne,
                    date, gender, userName, avatar);
            UUID id = newUser.getId();
            if(userDBManagement.addUser(newUser) && userDBManagement.getUser(id) != null){
                req.getSession().setAttribute("authenticatedUser", newUser);
                resp.sendRedirect(req.getContextPath() + "/profile");
            } else {
                req.setAttribute("ErrorMsg", "Error creating user");
            }
    
        }
  
    
        //manage input from parts to string
        private String manageInput(Part part) throws IOException {
            InputStream in = part.getInputStream();
            StringBuilder sb = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String read;
    
            while ((read=br.readLine()) != null) {
                sb.append(read);
            }
            br.close();
            return sb.toString();
        }
    
    }

Below is my function from JSP file that is supposed to bring the infos about the user after register
    //this ajax call brings info about the user -> last name, path to profile pic and username
window.onload = jsonData();
function jsonData() {
    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if(this.readyState == 4 && this.status == 200){
            const resp = JSON.parse(this.responseText);
            document.getElementById("name").innerText = resp.name;
            const path = resp.path;
            const img = document.createElement('img');
            img.src = path;
            document.getElementById('img').appendChild(img);

        }
    }
    xhttp.open("POST", "profile", true);
    xhttp.send();
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Sorin
  • 111
  • 1
  • 6
  • Do watch your typing. (a) Use an apostrophe for contractions, not a back-tick. A back-tick is interpreted as Markdown formatting. (b) Use proper case such as `I` versus `i` in your text. This site is meant to be more like Wikipedia and less like a chat room. – Basil Bourque Nov 22 '20 at 09:25
  • Does this address your issue: [*Simplest way to serve static data from outside the application server in a Java web application*](https://stackoverflow.com/q/1812244/642706)? – Basil Bourque Nov 22 '20 at 09:28
  • It's my first or second question on the website. Thanks for the tips. Yes, somehow it addresses the matter in hand, i also saw that yesterday, but i can't manage to make it work, in my case. I tought there is a simpler way than modifying the Context of the server.xml file in my Tomcat. – Sorin Nov 22 '20 at 10:24

0 Answers0