Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert InputStream to base64 string

Tags:

There is a way to convert an InputStream to a String, and encode it to base64, right?

In my function, I get InputStream parameter, 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 base 64 format.)

like image 211
foo Avatar asked Mar 08 '17 09:03

foo


People also ask

How to convert InputStream to Base64 in Java?

Converting InputStream to Base64 String Therefore, we need to first convert the file to an InputStream and then read the stream, byte-by-byte, into an array. We're using the IOUtils. toByteArray() method from the Apache commons-io package as a convenient alternative to the otherwise verbose Java-only approach.

What is Base64 encoding used for?

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with ASCII. This is to ensure that the data remain intact without modification during transport.


1 Answers

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

like image 125
mhasan Avatar answered Sep 21 '22 22:09

mhasan