如何在Android中将文件转换为base 64(如.pdf,.txt)?

Bas*_*eer 5 java base64 android

如何将SD卡文件(.pdf,.txt)转换为基本64字符串和字符串发送到服务器

Vru*_*tel 7

这种方法对我有用

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;
}
Run Code Online (Sandbox Code Playgroud)


Cha*_*ens -5

尝试这些代码

        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;
         }
Run Code Online (Sandbox Code Playgroud)

  • `loadFile` 方法在哪里? (2认同)