ZK MVVM上傳檔案範例如下。
index.zul
<zk>
<window apply="org.zkoss.bind.BindComposer" viewModel="@id('vm') @init('idv.matt.vm.MyVM')">
<div>
<fileupload label="上傳圖片" onUpload="@command('upload')" /><label value="@load(vm.uploadFileName)"/>
<image content="@load(vm.uploadImage)"/>
</div>
</window>
</zk>
在ViewModel的upload()
方法中利用@ContextParam
傳入隱含物件BindContext
並呼叫getTriggerEvent()
取得上傳事件來取得上傳的檔案。
MyVM.java
package idv.matt.vm;
import org.zkoss.bind.BindContext;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.image.Image;
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zul.Messagebox;
public class MyVM {
private Image uploadImage;
private String uploadFileName;
@Command
@NotifyChange({"uploadImage","uploadFileName"})
public void upload(@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx) {
UploadEvent event =(UploadEvent) ctx.getTriggerEvent();
Media media = event.getMedia();
if(media instanceof Image) {
uploadImage = (Image) media;
uploadFileName = media.getName();
} else {
Messagebox.show("Not an image: "+ media, "Error", Messagebox.OK, Messagebox.ERROR);
}
}
// getter and setter ommitted
}
參考:
沒有留言:
張貼留言