2016-10-22 63 views
0

你好,我正在嘗試構建一個web應用程序,用戶可以在其上面上傳圖片。所以,我有表的用戶和圖像作爲該表中的行中的BLOB和我現在想找回它,利用一個Java servlet,但我只得到一個小的空白square.my代碼:Java Servlet Mysql Blob image

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
import java.sql.*; 

public class Profile extends HttpServlet { 

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    response.setContentType("text/html;charset=UTF-8"); 
    ServletOutputStream out = response.getOutputStream(); 
    try{ 

    Class.forName("com.mysql.jdbc.Driver"); 

     Connection con=DriverManager.getConnection 
       ("jdbc:mysql://195.251.267.131:3306/****","****","****"); 

    PreparedStatement ps=con.prepareStatement 
       ("select * from users where email=?"); 
HttpSession session=request.getSession(false); 
if(session!=null){ 
String email=(String)session.getAttribute("email"); 
Blob photo = null;      
    ps.setString(1, email); 

    ResultSet rs =ps.executeQuery(); 
     while(rs.next()) { 
    photo = rs.getBlob(1); 
    } 
    response.setContentType("image/jpg"); 
    InputStream in = photo.getBinaryStream(); 
    int length = (int) photo.length(); 

    int bufferSize = 1024; 
    byte[] buffer = new byte[bufferSize]; 

    while ((length = in.read(buffer)) != -1) { 
    System.out.println("writing " + length + " bytes"); 
    out.write(buffer, 0, length); 
    } 

     in.close(); 
    out.flush(); 
     } 
    } 
} 
+0

也許會通過調試程序並檢查收到的內容,然後在此處寫入?你還應該檢查你的客戶端,確保它發送了一些東西。 – shinzou

回答

0

我在代碼中看到一些可能的原因:

  • 不要在開始處設置contentType = text/html。這是沒有用的。
  • 右邊mimetype for jpg imagesimage/jpeg

此外,我還建議這些小的修改:

  • 請勿初始化length=photo.length。這是沒有用的。
  • 使用4096的倍數的緩衝區大小。它更高效。
  • Appart酒店從做out.flush(),你也應該關閉打開的流(outin),preferrably在try-與資源指令:

try(OutputStream out=response.getOutputStream()) { ... }

同爲JDBC資源:連接,語句和結果集。

  • 當session == null時,您應該考慮另一種行爲。例如,用描述性消息拋出ServletException
+0

我試過修復你建議並暫時刪除,如果(會話!=空),我得到的結果仍然是我的頁面右上角的空白sqare相同 – groundslam

+0

Ples通過直接從瀏覽器調用它來測試你的servlet地址欄:'http:// server:port/context/servlet',並查看服務器返回的響應是什麼。 –