ZK 上傳圖片和顯示圖片(保存在文件夹)

上傳圖片:

前台代码:

<div  width="19%" style="float:right;clear:right;overflow:hidden;">
    <grid>
    <columns>
     <column width="100%"></column>
    </columns>
    <rows>
     <row><div width="100px" height="200px">
       <image id="memberPhoto" src=""/>
     </div></row>
    </rows>
    </grid>
    <separator />
    <button label="上傳相片" onClick="winInfo.upload()"/>
   </div>

后台代码:

upload Event:

public void upload() throws InterruptedException,IOException,SQLException{
  Configuration config=this.getDesktop().getWebApp().getConfiguration();
  config.setMaxUploadSize(1024); // 單位 KB ,如果為負則不限制大小
  Object media=org.zkoss.zul.Fileupload.get("選擇文件","相片上傳");
  if(media==null)
   return;
  if(!(media instanceof org.zkoss.image.Image)){
   Messagebox.show("此文件不是圖片類型,請檢查!","Error",Messagebox.OK,Messagebox.ERROR);
   return;
  }
  org.zkoss.image.Image image=(org.zkoss.image.Image)media;
  String fileName=image.getName().toLowerCase();
  memberPhotoType=fileName.substring(fileName.length()-3);//图片的类型
  memberPhotoInputStream=image.getStreamData();//图片的InputStream
  Image memberImage=(Image)this.getFellow("memberPhoto");
  memberImage.setContent((org.zkoss.image.Image)media);//将图片放入<image>里
 }

public void save() throws IOException{

   Desktop dtp=Executions.getCurrent().getDesktop();

   String realPath=dtp.getSession().getWebApp().getRealPath("/upload/member_photo/")+"/";查找存放文件的路径   

   File file=new File(realPath+"文件名");

   Files.copy(file,memberPhotoInputStream);

   Files.close(r);

}

显示图片

public void load() throws IOException{

  Desktop dtp=Executions.getCurrent().getDesktop();

  String realPath=dtp.getSession().getWebApp().getRealPath("/upload/member_photo/")+"/"+memberPhotoPath;

  AImage aImg=new AImage(realPath);//这个是关键

  Image memberImage=(Image)this.getFellow("memberPhoto");

  memberImage.setContent(aImg);

}

原文地址:https://www.cnblogs.com/TankMa/p/1962135.html