Reputation: 404
How to covert the SD-card documents (.pdf,.txt) to base 64 string and string send to the server
Upvotes: 9
Views: 20742
Reputation: 2441
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;
}
Upvotes: 8
Reputation: 1582
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;
}
Upvotes: -5
Reputation: 2606
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.
Upvotes: 2