用Java从MySQL读取blob

我在使用Java从MySQL数据库中读取blob时遇到问题。 我需要用jax-rs编写一个web服务来提供保存在数据库中的图像。 对于传输,必须使用Base64进行编码。

这是我的代码:

public String getImage(@PathParam("id") int id) throws SQLException{ System.out.println(id); String img64str = "null"; Blob image = null; Connection conn = MySQLConnection.getInstance(); if(conn != null) { try{ // Anfrage-Statement erzeugen. Statement query; query = conn.createStatement(); // Ergebnistabelle erzeugen und abholen. String sql = "SELECT bild FROM beitraege where id="+id; ResultSet result = query.executeQuery(sql); //Ergebniss zur ckliefern while (result.next()) { System.out.println("while"); image = result.getBlob("bild"); InputStream binaryStream = image.getBinaryStream(1, image.length()); String str= binaryStream.toString(); byte[] bdata=str.getBytes(); byte[] img64 = Base64.encode(bdata); img64str = new String(img64); } }catch (SQLException e) { e.printStackTrace(); } } return img64str; } 

不知何故,它只返回这样的东西(显示结果列表解码):

 java.io.ByteArrayInputStream@cc90a0a 

问题出在“toString()”调用: binaryStream.toString(); BinaryInputStream不实现toString() 。 使用这样的东西来读取字节:

 int ch; //read bytes from ByteArrayInputStream using read method while((ch = binaryStream.read()) != -1) { System.out.print((char)ch); // store it to an array... } 

java.io.ByteArrayInputStream@cc90a0a是在InputStream上调用toString()的结果。 它实际上并没有将它转换为String – 它只是使用默认的toString()行为来返回当前环境中对象的标识符。

InputStream接口上定义了几个read()方法,以获取由流表示的基础字节序列。 您需要使用其中一个来提取内容,而不是尝试通过toString()将其转换为String

您将返回binaryStream.toString()的结果,类似于“java.io.ByteArrayInputStream@cc90a0a”。

您必须使用InputStream上的read方法来获取实际内容。

这条线错了:

 binaryStream.toString(); 

InputStream不会覆盖toString() ,因此使用Object.toString() ,它是这样定义的。 这就解释了为什么你要获得String

这个问题向您展示了如何正确地从InputStream转换为String

这表示你不应该将二进制数据(如Base64编码的图像)转换为字符串(请参阅下面的NullUserException注释)。