Wednesday, 16 November 2011

Get Image using Ajax apart from Text/XML response


When we use Ajax then we can only get Text/XML response using the url.
With the help of the below procedure we can also get the image using ajax.


The Client side programming is something like: 

<html>
<head>
<script>
   function createGraphs(){
            var xmlhttp;
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    var imageResponse = xmlhttp.responseText;
                    changeImage(imageResponse);
                }
            }

     xmlhttp.open("POST","GetImageResponse.do",true);
            xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlhttp.setRequestHeader("Content-length", params.length);
            xmlhttp.setRequestHeader("Connection", "close");
            xmlhttp.send(params);
            xmlhttp.send();
        }

  function changeImage(type,imageResponse){
            document.getElementById("graph").src = "data:image/png;base64,"+imageResponse;
        }
</script>
</head>
<body>
 <img alt = "graph" id = "graph" name="linechart" src="" />
 <input type="button" value="get Image" onclick="createGraphs()"/>
</body>
</html>


On click of the button a ajax response is sent to the server & receives text type response which is added to the source of the image tag as


document.getElementById("graph").src = "data:image/png;base64,"+imageResponse;



The Server side programming is something like:



 //Struts Action Method
 public ActionForward execute (final ActionMapping mapping,
                                  final ActionForm form,
                                  final HttpServletRequest request,
                                  final HttpServletResponse response) throws Exception {
        final byte[] chartbytes = this.getBytesFromFile (new File ("C:/Image.png"));
        final BufferedInputStream buf = null;
        ServletOutputStream myOut = null;

        try {
            myOut = response.getOutputStream ();
            // set response headers
            response.setContentType ("application/png");

            final String filename = "graph.png";
            (response).addHeader ("Content-Disposition", "attachment; filename=" + filename);
            response.setContentLength (chartbytes.length);
            myOut.write (chartbytes);
        } catch (final IOException e) {
            System.err.println ("Exception::" + e.getMessage ());
        } finally {
            if (myOut != null) {
                myOut.close ();
            }
            if (buf != null) {
                buf.close ();
            }
        }
        return null;
    }

    // Returns the contents of the file in a byte array.
    public byte[] getBytesFromFile (final File file) throws IOException {
        final InputStream is = new FileInputStream (file);

        // Get the size of the file
        final long length = file.length ();

        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }

        // Create the byte array to hold the data
        final byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while ((offset < bytes.length) && ((numRead = is.read (bytes, offset, bytes.length - offset)) >= 0)) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException ("Could not completely read file " + file.getName ());
        }

        // Close the input stream and return bytes
        is.close ();
        return bytes;
    }


So, in this way one can transfer the images to client side using ajax

No comments:

Post a Comment