Home » Java » java – Image not uploading in servlet Ajax-Exceptionshub

java – Image not uploading in servlet Ajax-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

i am creating simple file uploading system in servlet ajax. when i tried to upload the file file is not uploaded what i tried so far i attached below. JQuery i think it is fine. i don’t have idea about servlet i am a beginner of servlet. i need to upload the file. i am tring this last 2 days still problem is there . servlet code is correct what i written.any mistake

Form

<div align="left">
                <label>Photo</label>
                <input name="logo" type="file" id="logo" name="logo" class="dropify_" data-default-file="">
            </div>
            <div class="row">
                <div id="logo_" class="col-md-3">
                </div>
            </div>

JQuery

<script>
        var dvE = $('#logo').dropify({
        });
        dvE = dvE.data('dropify')


        function addEmployee()
        {
            var form = $('#frmemployee')[0];
            var formdata = new FormData(form);
            $.ajax({

                type : 'POST',
                url : 'upload',
                data : formdata,

                contentType: false,
                processData: false,

                success: function(data)
                {
                     alert("success");
                    $('#frmemployee')[0].reset();

                }

            });
        }

    </script>

Servlet

      @MultipartConfig(maxFileSize = 1024 * 1024 * 2)
@WebServlet("/upload")
public class upload extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {


        PrintWriter out = response.getWriter();

                response.setContentType("text/html");


        // Getting File data
        Part part = request.getPart("logo");
        out.println(part);    
        // Getting Application Path
        String appPath = request.getServletContext().getRealPath("");

        // File path where all files will be stored
        String imagePath = appPath + "images";

        // Creates the file directory if it does not exists
        File fileDir = new File(imagePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        //Get Image Name
        String imageName = part.getSubmittedFileName();

        if(validateImage(imageName)){
            try{
                part.write(imagePath + File.separator + imageName);
                out.print("<img src=\"images/"+imageName+"\" >");
            }catch (Exception ex) {
                out.print("<h1>"+ex.getMessage()+"</h1>");
            }
        }else{
            out.print("<h1>Invalid Image Format</h1>");
        }
    }

    //Validates uploaded file is Image or not
    private boolean validateImage(String imageName){
        String fileExt = imageName.substring(imageName.length()-3);
        if("jpg".equals(fileExt) || "png".equals(fileExt) || "gif".equals(fileExt))
            return true;

        return false;
    }

    }
How to&Answers: