Search code examples
javajspjsp-tags

image upload working on localhost fine but not in server in jsp


Image upload working on localhost fine using request.getRealPath() but same we are using in server that's not

working, because server can not find specified path.. image can't be displayed .. how i can solved this problem.??

here is code for image uploading:

           filePath =request.getRealPath("") + "\\img\\";                 
            System.out.println(filePath);
        String contentType = request.getContentType();

        if ((contentType.indexOf("multipart/form-data") >= 0)) 
        {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List fileItems = upload.parseRequest(request);
                   //  message=    fileItems.get(2).toString();



            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                                 if(fi.isFormField())
                                 {
                                     message=fi.getString();
                                     System.out.println("message is  : "+message);
                                     bean.setEmp_id(Integer.parseInt(message));
                                 }
                if (!fi.isFormField()) {
                    String fieldName = fi.getFieldName();
                    System.out.println("field name"+fieldName);
                    fileName = fi.getName();




                    if (fileName.lastIndexOf("\\") >= 0) {
                        file = new File(filePath
                                + fileName.substring(fileName
                                        .lastIndexOf("\\")));

                    } else {
                        file = new File(filePath
                                + fileName.substring(fileName
                                        .lastIndexOf("\\") + 1));

                    }
                    fi.write(file);

Solution

  • The getRealPath() gives the absolute path (on the file system) leading to a file specified in the parameters of the call. It returns the path in the format specific to the OS.

    Read request#getRealPathfor its documentation.

    Also it is advised to use servletRequest.getSession().getServletContext().getRealPath("/") instead of servletRequest.getRealPath("/") as it is deprecated.

    so the best way is to provide the upload path for the server by yourself, as the method values specific to the OS the returned path may not be accessible(Permissions).

    Hope this helps !!