将 InputStream 转换为 base64 字符串

Convert InputStream to base64 string

有一种方法可以将 InputStream 转换为 String,并将其编码为 base64,对吗?

在我的函数中,我得到了 InputStream 参数,并且需要将它插入到我的 Oracle 数据库中的 BLOB 字段中 table。

有办法吗?

(我的数据库对象包含用于保存图像的字符串字段,但我找不到任何方法将 InputStream 转换为 base 64 格式的字符串。)

最简单的方法是使用 apache-commons 中的 IOUtils 来做到这一点:

String result= IOUtils.toString(inputStream, ENCODING); 

来自文档:

toString(byte[] input, String encoding) Gets the contents of a byte[] as a String using the specified character encoding.

之后 Encode/Decode Base64:

// Encode 
String resultBase64Encoded = Base64.getEncoder().encodeToString(result.getBytes("utf-8"));


// Decode
byte[] asBytes = Base64.getDecoder().decode(resultBase64Encoded);
String resultAsStringAgain= String(asBytes, "utf-8")

注意: 我假设您使用 JDK 8 作为 Encode/Decode 部分。

显然,OP 只想将 InputStream 持久保存到数据库。您可以直接使用 JDBC:

InputStream inputStream = ......;
String sql = "INSERT INTO TABLE_NAME(COLUMN_NAME) values (?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setBlob(1, inputStream);
statement.executeUpdate();

您可以使用 Base64 来尝试这样的事情 API。

InputStream finput = new FileInputStream(file);
byte[] imageBytes = new byte[(int)file.length()];
finput.read(imageBytes, 0, imageBytes.length);
finput.close();
String imageStr = Base64.encodeBase64String(imageBytes);

使用这个:

http://commons.apache.org/proper/commons-codec/archives/1.9/apidocs/org/apache/commons/codec/binary/Base64.html

正如我提到的,您不应该对二进制数据使用 String。不过,base64 编码的数据可以存储为字符串。但是由于您的数据库列是一个 blob,我会继续使用 byte[].

使用 IOUtils 从 InputStream 得到一个 byte[]:

byte[] bytes = IOUtils.toByteArray(yourInputStream);
byte[] encoded = java.util.Base64.getEncoder().encode(bytes);

然后写入数据库。使用 jdbc 和 PreparedStatement 编写 blob 如下所示:

yourPreparedStatement.setBytes(nIndex, encoded);

有一个很好的方法是使用 IOUtils 将 InputStream 转换为 Byte Array...

类似

    InputStream is;
    byte[] bytes = IOUtils.toByteArray(is);

这里可以使用Base64Byte Array转换为String

示例代码

    String encoded = Base64.getEncoder().encodeToString(bytes);

现在您可以使用 String