1

How can I encode a ByteArrayInputStream from Java in React as a Blob or BASE64?

java.io.ByteArrayInputStream@584e2317

enter image description here

My Java Code:

Connection con = DriverManager.getConnection(url, props);

        final PreparedStatement stmt = con.prepareStatement("SELECT * FROM \"sg_Images\".\"Images\" ");
        ResultSet rs = stmt.executeQuery();

        JSONArray array = new JSONArray();
        while (rs.next()) {

            JSONObject obj = new JSONObject();

            obj.put("Bild", rs.getBinaryStream("foto"));
            obj.put("Datum", rs.getDate("datum"));

            array.put(obj);

        }

        response.setContentType("application/json");

        ServletOutputStream out = response.getOutputStream();
        out.print(array.toString());
        out.flush();
        out.close();

        rs.close();
        stmt.close();
        con.close();
schorle88
  • 103
  • 6

1 Answers1

0

The most simple solution is to read the InputStream and get the expected String.

Based on this Baeldung's arcticle, add this method:

private String getContent(InputStream inputStream) throws IOException{
    StringBuilder textBuilder = new StringBuilder();
    // Please do not forget to change the charset 
    // if you are not using UTF8 
    try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
        int c = 0;
        while ((c = reader.read()) != -1) {
            textBuilder.append((char) c);
        }
        return textBuilder.toString();
    }
}

...and call it when you build your JSON array

obj.put("Bild", getContent(rs.getBinaryStream("foto")));

Please note that it might not be a good idea to send all your blobs this way if the are big.

You can also find interesting solutions on Stackoverflow

C.Champagne
  • 5,381
  • 2
  • 23
  • 35