How to covert the SD-card documents (.pdf,.txt) to base 64 string and string send to the server
Asked
Active
Viewed 2.0k times
3 Answers
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
-
Can you please explain what is the meaning of the flag Base64.NO_WRAP? – Danish Ansari Apr 21 '20 at 10:55
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