How to convert a file to base 64 (like .pdf,.txt) in Android?

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

Answers


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;
         }

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.


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;
}

Need Your Help

Adding Users to Gitolite, Permission Denied

linux git gitolite public-key

I have a Gitolite server running on EC2 that works pretty well. I've added users before and have no problem adding repositories.

With PHPUnit Class 'mysqli' is not found

php mysqli phpunit

I just started with PHPUnit. Some simple tests I wrote are working. So in general PHPUnit is up and running. There's something wrong with the MySQLi class though.