Search code examples
imagegwtuploadbase64gwt-rpc

GWT client-side image upload & preview


I am using GWT and I want to upload an image and display its preview without interacting with the server, so the gwtupload lib does not look like a way to go.

After the image is uploaded and displayed, user can optionally save it. The idea is to send the image through GWT-RPC as a Base64 encoded String and finally store it in the DB as a CLOB.

Is there any easy way to do it either with GWT or using JSNI?


Solution

  • /**
     * This is a native JS method that utilizes FileReader in order to read an image from the local file system.
     * 
     * @param event A native event from the FileUploader widget. It is needed in order to access FileUploader itself.    * 
     * @return The result will contain the image data encoded as a data URL.
     * 
     * @author Dušan Eremić
     */
    private native String loadImage(NativeEvent event) /*-{
    
        var image = event.target.files[0];
    
        // Check if file is an image
        if (image.type.match('image.*')) {
    
            var reader = new FileReader();
            reader.onload = function(e) {
                // Call-back Java method when done
                imageLoaded(e.target.result);
            }
    
            // Start reading the image
            reader.readAsDataURL(image);
        }
    }-*/;
    

    In the imageLoaded method you can do something like logoPreview.add(new Image(imageSrc)) where the imageSrc is the result of loadImage method.

    The handler method for FileUpload widget looks something like this:

    /**
     * Handler for Logo image upload.
     */
    @UiHandler("logoUpload")
    void logoSelected(ChangeEvent e) {
        if (logoUpload.getFilename() != null && !logoUpload.getFilename().isEmpty()) {
            loadImage(e.getNativeEvent());
        }
    }