Loading
 
What's Next: View All Tutorial →

Spring MVC + Jquery File AJax Upload without page refresh

In this article you will learn how to upload file in ajax call without reloading page Refer  How to upload file image or document using Spring MVC MultipartHttpServletRequest   Action Class Method It accept the file in with Mult...

Published Date: 24/02/2015  Last Modified Date: 24/02/2015    New Post



In this article you will learn how to upload file in ajax call without reloading page

Refer  How to upload file image or document using Spring MVC MultipartHttpServletRequest

 

Action Class Method


It accept the file in with MultipartHttpServletRequest and return in the json format
 
    @RequestMapping("/saveAndViewApplicationData")
    public @ResponseBody
    Map saveApplicationForm(HttpServletRequest request) {
        Map resultMap = new HashMap();
        resultMap.put("extrakey", request.getParameter("extrakey"));
        resultMap.put("userName", request.getParameter("userName"));
        resultMap.put("gndr", request.getParameter("gender"));
        resultMap.put("extrakey1", request.getParameter("extrakey1"));
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("fileImg");

        String path = "D:/resource/img/" + multipartFile.getOriginalFilename().toLowerCase();

        resultMap.put("path", "/img/" + multipartFile.getOriginalFilename().toLowerCase());

        System.out.println(path);
        File file = new File(path);

        BufferedImage image = null;
        try {
            image = ImageIO.read(new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException ex) {
            System.out.println(ex);
        }

        try {
            if (multipartFile.getSize() >= 325000) {
                boolean status = ImageIO.write(resize(image, Method.ULTRA_QUALITY, 1000, Scalr.THRESHOLD_QUALITY_BALANCED), "JPG", file);
                image = ImageIO.read(file);
                if (status == false) {
                    return null;
                }
            } else if (multipartFile.getSize() >= 125000) {
                boolean status = ImageIO.write(resize(image, Method.ULTRA_QUALITY, 600, Scalr.THRESHOLD_QUALITY_BALANCED), "JPG", file);
                image = ImageIO.read(file);
                if (status == false) {
                    return null;
                }
            } else {
                multipartFile.transferTo(file);
            }

        } catch (IOException ex) {
            System.out.println(ex);
        }
        return resultMap;
    }
 

Webpage

 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script src="<%=request.getContextPath()%>/jquery.js"></script>
        <script src="<%=request.getContextPath()%>/jquery.fileupload.js"></script>
    </head>
    <body>
        <h1>Application Form</h1>
        <form name="appFrm" id="appFrm" action="<%=request.getContextPath()%>/saveAndViewApplicationData" enctype="multipart/form-data" method="post">
            <table>
                <tr>
                    <td>Name:</td>
                    <td><input type="text" name="userName" value="john" id="userName"/><td>
                </tr>
                <tr>
                    <td>Gender: </td>
                    <td>
                        <select name="gender">
                            <option value="M" selected="true">Male</option>
                            <option value="F">Female</option>                
                        </select>
                    <td>
                </tr>

                <tr>
                    <td>Photo : </td>
                    <td><input type="file" name="fileImg" id="fileImg"  /> 
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" id="submitButton" value="Submit"/>
                    </td>
                </tr>
            </table>
            <div id="progress" style="width:500px">
                <div class="progress-bar" style="background-color: black; height: 20px;width: 0px"></div>
            </div>

            <img id="imgresult" src="" alt="" />
            <div id="responseSec" style="height: 50px"></div>
        </form>
        <script type="text/javascript">



            function validateForm() {
                if ($('#userName').val() === '1') {
                    alert('hi');
                    return false;
                }
            }
            $(document).ready(function() {
                $('#appFrm').on('submit', function(e) {
                    e.preventDefault();

                });

                //this event invoked when the file is selected in the file input
                $('#appFrm').bind('fileuploadsubmit', function(e, data) {

                    alert('form submit event');
                    if (validateForm() === false) {
                        return false;
                    }
                    //validation place, if some validation is failed, we can update the data.context and return false
                    if ($('#userName').val() === '1') {
                        data.context = data.context.text('Enter correct value and upload again');
                        return false;
                    }

                    //extra form data you can send
                    data.formData = {
                        'extrakey': 'extravalue',
                        'extrakey1': 'extravalue1'
                    };
                });

                $('#appFrm').fileupload({
                    dataType: 'json',
                    add: function(e, data) {
                        alert('add event raising after file completed');
                        $("#submitButton").unbind("click");
                        $('#submitButton')
                                .click(function() {
//                                    data.context = $('<p/>').text('Uploading...').replaceAll($(this));
                                    if (validateForm() === false) {
                                        return false;
                                    } else {
                                        data.submit();
                                    }
                                });
                    },
                    done: function(e, data) {
                        alert('done event raising after upload completed');

                        var contextPath = '<%=request.getContextPath()%>';
                        $("#submitButton").unbind("click");



                        $('#imgresult').attr('src', contextPath + data.result.path);
                        //html response for the file upload request
                        $('#responseSec').html(data.result.extrakey + data.result.extrakey1 + data.result.userName + data.result.gndr);
                    },
                    progressall: function(e, data) {
                        var progress = parseInt(data.loaded / data.total * 100, 10);
                        $('#progress .progress-bar').css('width', progress + '%');
                    }
                });
            });
        </script>

    </body>
</html>


Plugin Reference

https://github.com/blueimp/jQuery-File-Upload

 

Download Project


https://drive.google.com/file/d/0B_9jt9kIlxciSnIzUHJrTDV5VzA/view?usp=sharing
Awaiting for Administrator approval





Tags: Forms Handling Spring MVC

← Back to list


Related Post




×