有一种方法可以将InputStream
转换为String
,并将其编码为base64,对吗?
在我的函数中,我获得了InputStream
参数,并且需要将它插入到我的Oracle数据库表的BLOB字段中。
有没有办法做到这一点?
(我的数据库对象包含用于保存图像的字符串字段,但我找不到任何方法将InputStream
转换为base64格式的字符串。)
发布于 2017-03-08 18:03:08
您可以使用Base64应用编程接口来尝试这样的操作。
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);
使用以下命令:
发布于 2017-03-08 18:17:39
正如我所提到的,您不应该对二进制数据使用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);
https://stackoverflow.com/questions/42667942
复制相似问题