0

I'm trying to convert files to Base64 string. For small size file it works perfectly, for files larger like 500mb it throws OutOfMemoryError. I'm to convert the file to Base64 encodedString because it is my server side requirement to upload a file through Base64 encodedstring. is it possible to convert and send a 500mb file through this method ? Thanks in advance.

byte[] bytes = null;
            InputStream inputStream;
            try {
                inputStream = new FileInputStream(mFilepath);
                byte[] buffer = new byte[1024];
                int bytesRead;
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                try {
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        output.write(buffer, 0, bytesRead);
                    }
                    inputStream.close();
                    output.flush();
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                bytes = output.toByteArray();
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }

            // Here it throws OutOfMemoryError 
            String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);

Then I'm passing encodedString to server using HttpURLConnection.

Sai
  • 15,188
  • 20
  • 81
  • 121
  • may be this will help http://stackoverflow.com/questions/9630430/upload-large-file-in-android-without-outofmemory-error – Emil Aug 13 '15 at 11:37

1 Answers1

0

for files larger like 500mb it throws OutOfMemoryError

Of course. The heap limit of a Java-based Android app is going to be a lot smaller than 500MB, let alone two copies of the data, one in an expanded (Base64) format. There are hundreds of millions of devices that do not even have that much RAM for the whole device, let alone for use by your app.

is it possible to convert and send a 500mb file through this method ?

Only if you can somehow stream up the converted bytes. Convert a handful of bytes, write them to the socket, convert the next handful of bytes, write them to the socket, and so forth. You have no practical way of converting the entire 500MB file into Base64 in memory and transferring it as a string.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491