android - Android附件/文件选择器进入InputStream字符串
问题描述
我想创建一个类似于下图的功能。允许用户从设备中选择图像/pdf文件并将文件转换为输入流作为字符串并发送到服务器。
我已经通过这个在Android应用程序中附加任何类型的文件?并成功调用文件,但没有相机选项。感谢我可以参考的任何来源或能够执行此操作的库:
//Json that server going to receive
"Attachment": {
"InputStream": "string",
"FileName": "string"
}
/*My Code*/
public void goToAttachment(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*|application/pdf");
startActivityForResult(Intent.createChooser(intent, null), SELECTFILE_RESULT_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
switch (requestCode){
case SELECTFILE_RESULT_CODE:
if(resultCode == RESULT_OK){
fileSrc = data.getData().getPath();
}
break;
}
}
解决方案
您可以使用以下代码获取第Bitmap
一个图像,然后String
从Bitmap
对象获取:
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
switch (requestCode){
case SELECTFILE_RESULT_CODE:
if(resultCode == RESULT_OK){
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
String bmpString= bitMapToString(bitmap)
cursor.close();
}
break;
}
}
您可以使用以下方法转换Bitmap
为String
:
public String bitMapToString(Bitmap bitmap){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
String temp=Base64.encodeToString(b, Base64.DEFAULT);
return temp;
}
您可以更改Bitmap
压缩格式JPG
或PNG
与您的图像相同。
对于 PDF 和其他文件,您可以使用以下方法将其转换为字符串。
private String getString(String filepath) throws IOException {
InputStream inputStream = new FileInputStream(filepath);
byte[] byteArray = IOUtils.toByteArray(inputStream);
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
要获取文件路径,您可以使用以下代码:
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
推荐阅读
- javascript - 数组 - 求和
- python - 从输入形成多项式
- php - Laravel 中的图片上传无法在共享主机上查看
- vb.net - VB.net 正则表达式从字符串中排除某些字符
- c# - 我对 Unity 中的 Physics2D.BoxCast 感到困惑
- scala - Scala中的FlatMap
- django - 自定义用户子类化 AbstractUser 在列表视图模板中调用时给出 NoReverseMatch
- python - 如何在discord py中给用户硬币?
- three.js - 三 JS 导入模型尺寸和性能
- php - Laravel - 可选地包括 api 资源关系