Reputation: 123
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?
Upvotes: 0
Views: 1543
Reputation: 11
Let's say you have camera property which is an instance of FileUploader do the following:
camera.getElement().setAttribute("accept", "image/*");
camera.getElement().setAttribute("capture", "camera");
camera.getElement().setClassName("camera");
And have imgPreview an instance of Image, do the following.
imgPreview.getElement().setAttribute("id", "camera-preview");
imgPreview.getElement().setAttribute("src", "#");
imgPreview.getElement().setAttribute("alt", "#");
Now add a handler on camera object which calls a native method test1(NativeEvent)
camera.addChangeHandler( e-> {
test1(e.getNativeEvent());
});
public static native void test1(NativeEvent event) /*-{
var image = event.target.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$wnd.$('#camera-preview').attr('src', e.target.result);
}
// Start reading the image
reader.readAsDataURL(image);
}-*/;
Upvotes: 0
Reputation: 123
/**
* 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());
}
}
Upvotes: 1
Reputation: 41089
This document answers your question:
Reading files in JavaScript using the File APIs
Upvotes: 1