2015-07-03 38 views
0

我有問題想獲取從數據庫中的圖像,然後顯示在JSP頁面中他們:如何從數據庫中查看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> 
+0

您的JSP頁面上需要一些機制將'byte []'數據轉換爲圖像 –

+0

使用'stream'結果。 –

+1

由於到目前爲止發佈的答案相當黑客和可怕,下面是簡單的JSP/Servlet方式的詳細解釋,完全獨立於Struts或您正在使用的任何MVC框架:http://stackoverflow.com/questions/2340406/如何對檢索和顯示圖像從 - 一個數據庫-IN-A-JSP頁面 – BalusC

回答

1

什麼,你會收到你的JSP頁面將是原始的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頁面上的小工具設置

<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> 

致電上述功能的base64數據:

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

注:在我的情況,我顯示GIF文件,您可以根據您的要求進行更改。

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

0

明顯的用法是將圖像數據移動到某個集合,即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會話。

相關問題