2014-12-07 59 views
2

我有一個按鈕來拾取圖像並將其放入MySQL數據庫。在此之後,我希望圖像將顯示在同一頁面中。我是Struts2的新手,我現在不知道如何繼續。使用Struts 2在MySQL頁面查看圖像

這是我Registrazione.java類:

public String visualizzaimg() throws SQLException, IOException { 
    Connessione(); // DB connection method 
    PreparedStatement pstmt = con.prepareStatement("SELECT Immagine FROM Utenti WHERE Username = ?"); 
    pstmt.setString(1,username); 
    ResultSet rs = pstmt.executeQuery(); 
    while(rs.next()){ 
    fin = rs.getBinaryStream("Immagine"); 
    byte[] b = new byte[fin.available()]; 
    fin.read(b); 
    } 
    return "success"; 
} 

這是我struts.xml文件:

<action name="visualizzaimg" class="Model.Registrazione" method="visualizzaimg"> 
<result name="success" type="stream"> 
     <param name="contentType">image/jpeg</param> 
     <param name="inputName">fin</param> 
     <param name="contentDisposition">attachment;filename=${fileName}</param> /* Not sure if i've understood what i have to put here.. */ 
     <param name="bufferSize">1024</param> 
    </result> 
</action> 

這是我LoginRiuscito.jsp頁:

<s:form action="carica" id="carica" style="display:none" enctype="multipart/form-data"> 
    <s:textfield id="username" name="username" type="hidden"></s:textfield> 
    <s:file id="carica" name="caricaimg" accept="image/*"></s:file> 
    <s:submit value="Carica" ></s:submit> 
</s:form> 
<s:form action="visualizzaimg" enctype="multipart/form-data"> 
    <s:textfield id="username" name="username" type="hidden"></s:textfield> 
    <img src=""> //i don't know what i have to put in src.. 
    <s:submit value="Visualizza"></s:submit> 
</s:form> 

回答

1

的一點是寫網址到<img>標籤。該網址應該映射將數據流式傳輸到響應的操作。

<img src="<s:url action='visualizzaimg'/>"> 

動作需要返回stream結果,爲了這個目的,應該爲InputStream提供一個getter。輸入流的默認輸入名稱是inputStream,所以我們將使用它。

private InputStream inputStream; 

public ImputStream getInputStream(){ 
    return inputStream; 
} 

public String visualizzaimg() throws SQLException, IOException { 
    Connessione(); // DB connection method 
    PreparedStatement pstmt = con.prepareStatement("SELECT Immagine FROM Utenti WHERE Username = ?"); 
    pstmt.setString(1,username); 
    ResultSet rs = pstmt.executeQuery(); 
    if(rs.next()){ 
     inputStream = rs.getBinaryStream(1); 
    } 
    return "success"; 
} 

現在配置結果

<result name="success" type="stream"> 
    <param name="contentType">image/jpeg</param> 
</result> 
+0

它的工作!但你能解釋一下嗎?爲什麼你把1放在getBinaryStream中? 'inputStream = rs.getBinaryStream(1);' – Renny 2014-12-07 13:31:57

+0

因爲[this](https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getBinaryStream%28int%29)方法使用'int'類型的列索引參數。 – 2014-12-07 13:48:11

+0

...你可以在頁面上找到一個從1開始計數的參數。 – 2014-12-07 13:56:53