2014-04-22 291 views

回答

0

試試這個代碼在你servlet文件,因爲它會更容易使用和識別錯誤而不是JSP

import java.sql.*; 
import java.io.*; 
public class RetrieveImage { 
public static void main(String[] args) { 
try{ 
Class.forName("YOUR DRIVER NAME"); 
Connection con=DriverManager.getConnection(
"URL","USERNAME","PASSWORD"); 

PreparedStatement ps=con.prepareStatement("select * from TBL_NAME"); 
ResultSet rs=ps.executeQuery(); 
if(rs.next()){//now on 1st row 

Blob b=rs.getBlob(2); //2 means 2nd column data 
byte barr[]=b.getBytes(1,(int)b.length()); //1 means first image 

FileOutputStream fout=new FileOutputStream("d:\\IMG_NAME.jpg"); 
fout.write(barr); 

fout.close(); 
}//end of if 
System.out.println("ok"); 

con.close(); 
}catch (Exception e) {e.printStackTrace(); } 
} 
} 

現在你可以從上面給出的路徑加載圖像。

希望這有助於!

0

爲了在網絡上顯示圖像,您必須使用'img'標記並使用圖像的相對路徑填充它的'src'屬性。

現在的問題是'img'標籤不能將二進制數據視爲'src',即您的客戶端無法直接訪問數據庫中的文件。所以你可以做的是,創建一個Servlet,從數據庫加載文件,然後通過HttpServletResponse流式傳輸文件。

你的servlet將看起來是這樣的:

public class DispalyImage extends HttpServlet { 
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB. 

protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException 
{ 
    // Code to access database and get blob image. 
      // String id = HttpServletRequest.getParameter("id"); 
      // select from table where id='id' 

    Blob photo = rsimg.getBlob("thumbnails"); 

     response.reset(); 
      response.setBufferSize(DEFAULT_BUFFER_SIZE); 
    response.setContentType("image/jpeg"); 
    response.setHeader("Content-Length", String.valueOf(photo.length())); 

     // Prepare streams. 
    BufferedInputStream input = null; 
    BufferedOutputStream output = null; 

    try { 
     // Open streams. 
     input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE); 
     output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE); 

     // Write file contents to response. 
     byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 
     int length; 
     while ((length = input.read(buffer)) > 0) { 
      output.write(buffer, 0, length); 
     } 
    } finally {    
     output.close(); 
     input.close(); 
    }       

     } 
} 

現在的問題是,如何將你的servlet知道流,其形象?只需將您的密鑰作爲參數提供給Servlet。關鍵就可以用來加載圖像

假設你提供了關鍵的「身份證」,你將顯示圖像作爲

<img src="DisplayImage?id=imageId"></img> 

可以使用HttpServletRequest.getParameter(「ID」)方法獲取ID您的DisplayImage Servlet並使用該ID從數據庫加載圖像。

參考FileServlet by BalusC,它有很好的例子和解釋如何從數據庫提供文件。

相關問題