views:

552

answers:

4

Hi I wanted to upload images(along with other form details) and preview them, using jsp and servlets. I am able to do the uploading part but could not get, how to preview the images in the frontend.

I am using YUI to implement it. Actually I am trying to reuse an example which is implemented in PHP. I am attaching my Servlet code here. In this 'completeFileName' will be populated when a upload has been done.

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {            

            if(completeFileName == null) {
                PrintWriter pout = response.getWriter();
                JSONObject obj = new JSONObject();
                obj.put("hasError", new Boolean(true));
                pout.println(obj.toString());
            }
            try {

                OutputStream out = response.getOutputStream();
                Image image = Toolkit.getDefaultToolkit().getImage(completeFileName);
                ImageIcon icon = new ImageIcon(image);
                int height = icon.getIconHeight();
                int width = icon.getIconWidth();
  BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                ImageIO.write(bi, "jpg", out);
                out.flush();                
            } catch (Exception ex) {

            }

My Jsp code looks like this:

<script type="text/javascript" src="http://yui.yahooapis.com/2.3.0/build/connection/connection.js"&gt;&lt;/script&gt;
        <script type="text/javascript" src="http://yui.yahooapis.com/2.3.0/build/utilities/utilities.js"&gt;&lt;/script&gt;
        <script type="text/javascript">
            var $E = YAHOO.util.Event;
            var $  = YAHOO.util.Dom.get;
            var $D = YAHOO.util.Dom;
            function init(){
                var listImageHandler = {
                    success:function(o) {
                        var r = eval('(' + o.responseText + ')');
                        if(!r.hasError) {
                            var imageListCon = $('imageListCon');
                            var img = document.createElement('img');
                            //img.src = 'image.php?i=' + r.imageList[i];
                            img.src = r.fileName;
                            imageListCon.appendChild(img);
                        }
                    }
                };
                var onUploadButtonClick = function(e){
                    var uploadHandler = {
                        upload: function(o) {
                            //console.log(o.responseText);
                            $D.setStyle('indicator', 'visibility', 'hidden');
                            var r = eval('(' + o.responseText + ')');
                            if(r.hasError){
                                var errorString = '';
                                for(var i=0; i < r.errors.length; i++){
                                    errorString += r.errors[i];
                                }
                                alert(errorString);
                            }else{
                                YAHOO.util.Connect.asyncRequest('GET', 'UploadFileServlet', listImageHandler);
                            }
                        }
                    };
                    $D.setStyle('indicator', 'visibility', 'visible');
                    //the second argument of setForm is crucial,
                    //which tells Connection Manager this is an file upload form
                    YAHOO.util.Connect.setForm('testForm', true);
                    YAHOO.util.Connect.asyncRequest('POST', 'UploadFileServlet', uploadHandler);

                };
                $E.on('uploadButton', 'click', onUploadButtonClick);
                YAHOO.util.Connect.asyncRequest('GET', 'UploadFileServlet', listImageHandler);
            }

            $E.on(window, 'load', init);
        </script>        
    </head>
    <body>
        <form action="UploadFileServlet" method="POST" enctype="multipart/form-data" id="testForm">        
        <input type="file" name="testFile"><br>
        <input type="button" id="uploadButton" value="Upload"/>
        </form>
        <div class="restart"><a href="UploadFileServlet?redo=1">Redo It</a></div>
        <div  style="visibility:hidden; margin-bottom:1.5em;" id="indicator">Uploading... <img src="indicator.gif"/></div>
        <div id="imageListCon">

        </div>
    </body>

I am unable to get the response, can anyone help in this please ?

Thanks, Amit

+1  A: 

try this:

http://pixeline.be/experiments/jqUploader/

FrankBr
+1  A: 

Due to security limitations, you cannot preview the image on the front-end prior to uploading

K Prime
+1  A: 

If you are already able to upload the image in a folder at your server, you can easily display the image with a image control in your page. Let that folder be a temp folder which you may wish to empty after upload is completed. Then you first upload the file in the temp folder and display it to the user. If the user cancels the operation, you can delete the file from the folder.

But remember this will not be the real image preview as we generally visualize. But since this mimics the image preview, it may be a choice.

sangam
A: 

I don't know YUI, so I can't go in detail about this, but I can at least tell that there are several flaws in your logic: you're attempting to write the entire binary contents of the image back to the ajax response. This isn't going to work. In HTML you can only display images using an <img> element whose src attribute should point to a valid URL. Something like:

<img src="/images/uploadedimage.jpg">

To achieve this, just store the image at the local disk file system or a database at the server side and give in the ajax response the URL back with which the client can access the image. Let the ajax success handler create a DOM element <img> and fill its src value with the obtained URL.

You'll need to create a Servlet which listens on this URL and get the image as an InputStream from the local disk file system by FileInputStream or from the database by ResultSet#getBinaryStream() and writes it to the OutputStream of the response, along with a correct set of response headers with at least content-type. You can find here an example of such a servlet.

That said, you really don't need the Java 2D API for that. The Image and ImageIcon only unnecessarily adds much overhead. Just get it as an InputStream and write it the usual Java IO way to the OutputStream of the response.

BalusC
Hey Balusc thanks. I will be really greatful if you help me with the JS part also.
Amit
As said, I don't do YUI. I do plain JS or jQuery only.
BalusC
I guess YUI is making the things a lot complex. Plain JS or JQuery will serve the purpose. Can you please help me out with that.
Amit
It is not rocket science: 1) Ajax gets image URL as result. 2) Create img element in DOM. 3) set its src attribute with this URL as value. 4) make it to show in the page. That's all. Something like as this with jQuery: `succes: function(url) { $('<img/>').attr('src', url).appendTo($('#somediv')); }`
BalusC
Hi, I would like to know, the example in the link that you have quoted for servlet, is that servlet applicable for mulitpart form data implemented in jsp.
Amit
and how to get the url to be used in the image src from the output buffer in your code?
Amit
The request for the image counts as an entirely independent GET request. Effectively two requests are fired: 1) the multipart/form-data request to upload the image (and get the image URL as response). 2) a plain vanilla GET request to get the image (and the entire image contents as response). The URL is available as responsetext. It was just a basic example. You're the developer here, we just guide you how to develop.You can just use the servlet the same way (or didn't you do it at all? if so, checkout Apache Commons Fileupload). Do I have to develop for you?
BalusC