java convert inputStream to base64 string

╄→гoц情女王★ 提交于 2019-12-20 18:28:05

问题


There is a way to convert inputStream to a String, and encode it to base64, right? In my function, I get InputStream param, and need to insert it into the BLOB field in my Oracle database table. Is there a way to do that? (my database object contains string field to save the image, but I don't find any way to convert the inputStream to string in base64 format) Thank you!


回答1:


You can try something like this using the 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);

Use this:

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




回答2:


There is nice way to do this is using IOUtils to convert the InputStream into a Byte Array...

something like

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

Here you can use Base64 to convert Byte Array to String.

Sample Code

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

Now you can use your String.




回答3:


The simplest way would be to use IOUtils from apache-commons to do that:

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

From the documentation:

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

After that To Encode/Decode in Base64:

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


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

Note: I'm assuming you use JDK 8 for the Encode/Decode part.

Apparently the OP wants just to persist an InputStream to the DB. You can do that directly using JDBC:

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



回答4:


As I mentioned, you shouldn't use String for binary data. The base64-encoded data can be stored as a String though. But since your database column is a blob, I would continue to work with a byte[].

Use IOUtils to get a byte[] from the InputStream:

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

Then write it to the database. Writing a blob using jdbc and a PreparedStatement looks like this:

yourPreparedStatement.setBytes(nIndex, encoded);


来源:https://stackoverflow.com/questions/42667942/java-convert-inputstream-to-base64-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!