文件inputstream转base64
时间: 2023-08-12 20:09:38 浏览: 547
文件inputstream转base64的方法可以参考以下代码:
```kotlin
fun inputStreamToBase64(inputStream: InputStream): String {
val byteArrayOutputStream = ByteArrayOutputStream()
val buffer = ByteArray(1024)
var length: Int
try {
while (inputStream.read(buffer).also { length = it } != -1) {
byteArrayOutputStream.write(buffer, 0, length)
}
val data = byteArrayOutputStream.toByteArray()
return Base64.encodeToString(data, Base64.NO_WRAP)
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
inputStream.close()
byteArrayOutputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
return ""
}
```
这段代码将输入流中的数据读取到字节数组中,然后使用Base64编码将字节数组转换为Base64编码字符串。最后返回转换后的Base64编码字符串。请注意,这里使用的是Android的Base64类,如果是在Java环境中使用,需要使用java.util.Base64类。
#### 引用[.reference_title]
- *1* [安卓本地图片文件InputStream转换为Base64编码字符](https://blog.csdn.net/WiLL_XS/article/details/114583421)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [base64 InputStream互转](https://blog.csdn.net/holleyangyangs/article/details/120440983)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文