I ran into problems when choosing the path to the file of the file, I looked for all the stack overflows, but the problem was not solved. Code for selecting files from the device is shown below.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(Intent.createChooser(intent, "Choose File to Upload.."), PICK_FILE_REQUEST);
Selected files from the intention are obtained
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_FILE_REQUEST) {
if (data != null) {
Uri uri = data.getData();
String filePath = data.getData().getPath();
file = new File(filePath);
String name = getContentName(getContentResolver(), uri);
try {
InputStream inStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(bitmap);
attachFile.addView(imageView);
TextView textView = new TextView(this);
textView.setText(name);
attachFile.addView(textView);
return;
}
}
}
}
In the above code file path, `String filePath = data.getData () is obtained. getPath (); but when uploading files to the server, an exception is thrown as an invalid document and file. How to get the correct file path from uri?
But the file name is selected with
`public static String getContentName(ContentResolver resolver, Uri uri) {
Cursor cursor = resolver.query(uri, null, null, null, null);
cursor.moveToFirst();
int nameIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
if (nameIndex >= 0) {
return cursor.getString(nameIndex);
} else {
return null;
}
}`
How to get the correct file path for the selected file?