【问题标题】:How to convert a file to base 64 (like .pdf,.txt) in Android?如何在 Android 中将文件转换为 base64(如 .pdf、.text)?
【发布时间】:2014-02-06 11:12:32
【问题描述】:

如何将 SD 卡文档 (.pdf,.txt) 转换为 base 64 字符串并将字符串发送到服务器

【问题讨论】:

标签: java android base64


【解决方案1】:

这个方法对我有用

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

【讨论】:

  • 你能解释一下标志Base64.NO_WRAP是什么意思吗?
【解决方案2】:

您所要做的就是将文件读入字节数组,然后使用Base64.encodeToString(byte[], int) 将其转换为Base64 字符串。

【讨论】:

    【解决方案3】:

    试试这些代码

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

    【讨论】:

    • loadFile 方法在哪里?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2015-04-29
    • 2021-01-08
    相关资源
    最近更新 更多