Friday, 21 June 2013

Fetch Image Using Ajax

Introduction

One of the unsung heros in the HTML5 universe is XMLHttpRequest. Strictly speaking XHR2 isn't HTML5. However, it's part of the incremental improvements browser vendors are making to the core platform. I'm including XHR2 in our new bag of goodies because it plays such an integral part in today's complex web apps.
Turns out our old friend got a huge makeover but many folks are unaware of its new features. XMLHttpRequest Level 2 introduces a slew of new capabilities which put an end to crazy hacks in our web apps; things like cross-origin requests, uploading progress events, and support for uploading/downloading binary data. These allow AJAX to work in concert with many of the bleeding edge HTML5 APIs such as File System API, Web Audio API, and WebGL.

Fetching data

Fetching a file as a binary blob has been painful with XHR. Technically, it wasn't even possible. One trick that has been well documented involves overriding the mime type with a user-defined charset as seen below.

$('#linkImg').click(function(e){
                            e.preventDefault();
                            alert("hi");
                            var xhr = new XMLHttpRequest();
                            xhr.open('GET', '/users/exportA', true);
                            xhr.responseType = 'blob';

                            xhr.onload = function(e) {
                            if (this.status == 200) {
                            var blob = this.response;

                            var img = document.createElement('img');
                            img.onload = function(e) {
                            window.URL.revokeObjectURL(img.src); // Clean up after yourself.
                            };
                            img.src = window.URL.createObjectURL(blob);
                            document.body.appendChild(img);

                            }
                            };

                            xhr.send();
                            });

My Controller Code:

 @RequestMapping(value = "/users/exportA")
    @ResponseBody
    public void exportA(HttpServletResponse response)
            throws FileNotFoundException, IOException {

        response.setHeader("Content-Disposition", "inline;filename=Desert.jpg");

        OutputStream out = response.getOutputStream();
        response.setContentType("blob");
        FileCopyUtils.copy(new BufferedInputStream(new FileInputStream(
                "C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg")), out);

        out.flush();
        out.close();
    }

Require: jquery.min.js (Latest Version)


No comments: