如何将SD卡文件(.pdf,.text)转换为基本64字符串和字符串发送到服务器
答案 0 :(得分:2)
您所要做的就是将文件读取为字节数组,然后使用Base64.encodeToString(byte[], int)将其转换为Base64字符串。
答案 1 :(得分: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;
}
答案 2 :(得分:-4)
试试这些代码
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;
}