2016-10-22 36 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',并查看服务器返回的响应是什么。 –