GWT client-side image upload & preview

2019-08-29 19:38发布

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?

2条回答
叼着烟拽天下
2楼-- · 2019-08-29 20:21
/**
 * 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());
    }
}
查看更多
淡お忘
3楼-- · 2019-08-29 20:23

This document answers your question:

Reading files in JavaScript using the File APIs

查看更多
登录 后发表回答