【发布时间】:2014-02-06 11:12:32
【问题描述】:
如何将 SD 卡文档 (.pdf,.txt) 转换为 base 64 字符串并将字符串发送到服务器
【问题讨论】:
-
出租车你发布你的代码,你已经试过了。
-
使用此代码会有所帮助stackoverflow.com/a/47572643/3505534
如何将 SD 卡文档 (.pdf,.txt) 转换为 base 64 字符串并将字符串发送到服务器
【问题讨论】:
这个方法对我有用
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.encodeToString(byte[], int) 将其转换为Base64 字符串。
【讨论】:
试试这些代码
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 方法在哪里?