Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 296
Basheer Avatar asked Feb 06 '14 11:02

Basheer


People also ask

Can we convert file to Base64?

Convert Files to Base64Just select your file or drag & drop it below, press the Convert to Base64 button, and you'll get a base64 string. Press a button – get base64. No ads, nonsense, or garbage. The input file can also be an mp3 or mp4.

How do I change the path to Base64?

String value = Base64. encodeToString(bytes, Base64. DEFAULT);


Video Answer


2 Answers

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;
}
like image 53
Vrushi Patel Avatar answered Sep 19 '22 16:09

Vrushi Patel


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.

like image 39
pshegger Avatar answered Sep 21 '22 16:09

pshegger