9

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

Jonik
  • 80,077
  • 70
  • 264
  • 372
Basheer
  • 404
  • 2
  • 9
  • 17

3 Answers3

8

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,046
  • 4
  • 24
  • 49
Vrushi Patel
  • 2,361
  • 1
  • 17
  • 30
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,526
  • 24
  • 29
-4

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,568
  • 15
  • 30