8

How to covert the SD-card documents (.pdf,.txt) to base 64 string and string send to the server

Jonik
  • 77,494
  • 68
  • 254
  • 365
Basheer
  • 384
  • 2
  • 8
  • 17

3 Answers3

7

this method worked for me

String encodeFileToBase64Binary = encodeFileToBase64Binary(yourFile);    

private String encodeFileToBase64Binary(File yourFile) {
    int size = (int) yourFile.length();
    byte[] bytes = new byte[size];
    try {
        BufferedInputStream buf = new BufferedInputStream(new FileInputStream(yourFile));
        buf.read(bytes, 0, bytes.length);
        buf.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String encoded = Base64.encodeToString(bytes,Base64.NO_WRAP);
    return encoded;
}
Maelig
  • 2,020
  • 4
  • 26
  • 49
Vrushi Patel
  • 2,043
  • 1
  • 13
  • 29
2

All you have to do is read the file to a byte array, and then use Base64.encodeToString(byte[], int) to convert it to a Base64 string.

pshegger
  • 2,476
  • 25
  • 28
-5

Try these codes

        File dir = Environment.getExternalStorageDirectory();
        File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
        String encodeFileToBase64Binary = encodeFileToBase64Binary(yourFile);

        private static String encodeFileToBase64Binary(File fileName) throws IOException {
              byte[] bytes = loadFile(fileName);
              byte[] encoded = Base64.encodeBase64(bytes);
              String encodedString = new String(encoded);
              return encodedString;
         }
Charles Stevens
  • 1,510
  • 15
  • 29