问题描述
我正在使用GWT,并且我想上传图像并显示其预览而不与服务器交互,因此gwtupload lib看起来并不可行.
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.
上传并显示图像后,用户可以选择保存它.想法是通过GWT-RPC将图像作为Base64编码的字符串发送,最后将其作为CLOB存储在数据库中.
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.
是否可以通过GWT或JSNI进行简便的操作?
Is there any easy way to do it either with GWT or using JSNI?
推荐答案
/**
* 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);
}
}-*/;
在imageLoaded方法中,您可以执行logoPreview.add(new Image(imageSrc))之类的操作,其中imageSrc是loadImage方法的结果.
In the imageLoaded method you can do something like logoPreview.add(new Image(imageSrc)) where the imageSrc is the result of loadImage method.
FileUpload小部件的处理程序方法如下:
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());
}
}
这篇关于GWT客户端图片上传和下载预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!