Home > OS >  Java 1.6 Encode Base64 inputStream of a Excel file byte[] stream
Java 1.6 Encode Base64 inputStream of a Excel file byte[] stream

Time:09-24

I have been searching the web for this particular problem. Maybe i'm doing something wrong or i'm missing something here...

So i'm trying to convert a File Stream ( an Excel file ) -> mimetype ( application/octet-stream or application/vnd.ms-excel ) doesn´t matter...to a Base64 encoded string.

The reason i'm doing this is because i want to provide the File in a REST API inside a JSON object for later decoding in the browser the base64 string and download the file.

When I receivethe InputStream and save to the disk everything works fine...

Even when i use POSTMAN to get the FILE if I save the file it opens in Excel with all the right data.

THE CODE -> Used this simple enter image description here

Is it possible this is the problem ?

CodePudding user response:

I think you can ignore those warnings. Rather, the issue is here:

int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {   
    outputStream.write(buffer, 0, bytesRead);
}
:
String encodedBytesBase64 = Base64.encodeBase64String(buffer);

As you can see in the first part, you are reusing buffer to read the input stream and write to the output stream. If this loops around more than once, buffer will be overwritten with the next chunk of data from the input stream. So, when you are encoding buffer, you are only using the last chunk of the file.

The next problem is that when you are encoding, you are encoding the full buffer array, ignoring the bytesRead.

One option might be to read the inputStream and write it to a ByteArrayOutputStream, and then encode that.

int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
ByteArrayOutputStream array = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {   
    array.write(buffer, 0, bytesRead);
}
String encoded = Base64.encodeBase64String(array.toByteArray());
  • Related