【问题标题】:Java Servlet Mysql Blob imageJava Servlet Mysql Blob 映像
【发布时间】:2016-10-22 17:46:34
【问题描述】:

大家好,我正在尝试构建一个网络应用程序,用户可以在其中上传图片到他们的个人资料中。因此,我将表用户和图像作为该表上的一行中的一个 blob,现在我正在尝试使用 java servlet 检索它,但我只得到一个小的空白方块。我的代码:

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(); 
      }
   }
}

【问题讨论】:

  • 也许可以通过调试器逐步检查接收到的内容,然后将其写在这里?您还应该检查您的客户端以确保它发送了一些东西。

标签: java mysql servlets


【解决方案1】:

我在您的代码中看到了一些可能的原因:

此外,我还建议进行以下小修复:

  • 不要初始化length=photo.length。没用。
  • 使用 4096 的倍数的缓冲区大小。这样更有效。
  • 除了执行 out.flush() 之外,您还应该关闭打开的流(outin),最好在 try-with-resources 指令中:

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

对于 JDBC 资源也是如此:连接、语句和结果集。

  • 当 session==null 时,您应该考虑另一种行为。例如,抛出带有描述消息的ServletException

【讨论】:

  • 我尝试了您建议的修复并暂时删除了 if(session!=null),我得到的结果仍然是页面右上角相同的小边框空白方形
  • 请直接从浏览器地址栏调用 servlet:http://server:port/context/servlet 来测试您的 servlet,看看服务器返回的响应是什么。
猜你喜欢
  • 2017-09-12
  • 2023-03-21
  • 2011-07-09
  • 2018-06-26
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 2017-08-16
相关资源
最近更新 更多