Reputation: 41
I have a problem reading a blob from a MySQL database with Java. I need to write a webservice with jax-rs to deliver an image saved in the database. For transport, it has to be encoded using Base64.
This is my code:
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;
}
Somehow, it only returns something like this (shown result list decoded):
java.io.ByteArrayInputStream@cc90a0a
Upvotes: 1
Views: 20307
Reputation: 2476
java.io.ByteArrayInputStream@cc90a0a
is the result of calling toString()
on the InputStream
. It doesn't actually convert it into a String
- it just uses the default toString()
behavior of returning the identifier of the object within the current environment.
There are several read()
methods defined on the InputStream
interface to get at the underlying sequence of bytes represented by the stream. You'll need to use one of those to extract the content, rather than trying to convert it into a String
via toString()
.
Upvotes: 3
Reputation: 3963
The problem lies in the "toString()" call: binaryStream.toString();
BinaryInputStream do not implement toString()
.
Use something like this to read the bytes:
int ch;
//read bytes from ByteArrayInputStream using read method
while((ch = binaryStream.read()) != -1)
{
System.out.print((char)ch);
// store it to an array...
}
Upvotes: 3
Reputation: 25873
This line is wrong:
binaryStream.toString();
InputStream
does not override toString()
, thus uses Object.toString()
, which is defined like this. This explains why you're getting that String
.
This other question shows you how to correctly convert from InputStream
to String
.
This said you should not convert binary data (like Base64-encoded image) to string (see NullUserException's comments below).
Upvotes: -2
Reputation: 34313
You are returning the result of binaryStream.toString()
, which is something like "java.io.ByteArrayInputStream@cc90a0a".
You have to use the read methods on the InputStream to get the actual content.
Upvotes: 0