簡體   English   中英

如何從數據庫查看jsp頁面中的多個圖像?

[英]How to view more than one image in a jsp page from database?

我嘗試從db獲取圖像,然后在JSP頁面中顯示圖像時遇到問題:

ImageAction:

public class ImageAction {

private  byte[] itemImage;

public byte[] getItemImage() {
    return itemImage;
}

public void setItemImage(byte[] itemImage) {
    this.itemImage = itemImage;
}

public  void  execute() throws Exception{
      try {
          HttpServletResponse response = ServletActionContext.getResponse();
          response.reset();
          response.setContentType("multipart/form-data"); 
          byte[] imgData =(byte[])ServletActionContext.getRequest().getSession()
                           .getAttribute("imageData"); 
          System.out.println("imgData :: "+imgData);
          itemImage = imgData;
          ServletActionContext.getRequest().getSession().removeAttribute("imageData") ; 
          OutputStream out = response.getOutputStream();
          out.write(itemImage);
          out.flush();
          out.close();

      } catch (Exception e) {
          System.out.println("error :: ");
          e.printStackTrace();
      }
   //   return "success";
  }
}

jsp:

<tr >
    <td> <%= map.get(mapKey) %> </td>
    <td colspan="1" >
        <img src="<s:url value="ImageAction" />" width="115" border="0" />
    </td>   
</tr>

您將在JSP頁面上收到的將是raw byte[] ,您需要對其進行一些處理,請檢查以下內容:

<a src="" id="imageSrc"/>

一個簡單的anchor標記以顯示圖像。

以下代碼會將原始byte[]轉換為等效的Base64字符串,即顯示圖像必不可少。

<%
   byte data[]=request.getParameter(itemImage); //let itemImage for instance hold your data
   String encodedData=Base64.encodeBytes(data);
%>

現在,您需要在JSP頁面上使用一個小實用程序來設置base64數據

<script>
function imageBaseSixtyFourProcessor(baseSixtyFour){
    var img = new Image();
    img.src='';
        var imageUrl='data:image/gif;base64,'+baseSixtyFour;
        $('#imageSrc').attr('src',imageUrl);
        img.src = imageUrl;
    }
}
</script>

調用上面的函數:

<script>
  imageBaseSixtyFourProcessor(<%encodedData%>);
</script>

注意:就我而言,我正在顯示GIF文件,您可以根據需要進行更改。

同樣,您可以以相同的方式顯示多個圖像。

明顯的用法是將圖像數據移至某個集合,即Map 該操作應注意用於從地圖檢索圖像數據的mapKey

<s:iterator value="#session.imageDataMap">
  <img src="<s:url value="ImageAction"><s:param name="mapKey" value="%{key}"/></s:url>" width="115" border="0" /> 
</s:iterator>

如果從會話中獲取數據,則應修改代碼以使用集合。

...
Map<String, byte[]> imgDataMap =(Map<String, byte[]>)ActionContext.getContext().getSession().get("imageDataMap"); 
imageData = imgDataMap.get(mapKey);
System.out.println("imgData :: "+new Base64Encoder.encode(imgData));
itemImage = imgData;
...

在上面的示例中,使用了Struts 2會話映射而不是servlet會話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM