GWT client-side image upload & preview

为君一笑 提交于 2019-12-13 08:08:30

问题


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?


回答1:


This document answers your question:

Reading files in JavaScript using the File APIs




回答2:


/**
 * 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());
    }
}


来源:https://stackoverflow.com/questions/23944924/gwt-client-side-image-upload-preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!