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