Somnath Pal
Somnath Pal

Reputation: 1512

get name and full path of a file

I used Intent ACTION_GET_CONTENT to show recent files from phone memory. That includes images, pdf, google drive documents(pdf, xlsx) as shown in screenshot below. I want to get the name and full path so that I can upload the file to server. I/m getting the mime type correctly as of now.

public class MainActivity extends AppCompatActivity {

    Button btn;
    TextView txt;
    private final static int EXTERNAL = 111;
    private final static int ATTACH = 11;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button)findViewById(R.id.btn);
        txt = (TextView)findViewById(R.id.txt);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        photoIntent();
                    } else {
                        if (shouldShowRequestPermissionRationale(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            // showToast("Permission Required...");
                        }
                        requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL);
                    }


                } else {

                    photoIntent();
                }
            }
        });



    }

    private void photoIntent() {
        Intent intent = new Intent();
        Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath());
        intent.setDataAndType(uri, "*/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Complete action using"), ATTACH);
    }

    @Override
    public void onRequestPermissionsResult(int requestcode, String[] permission, int[] grantRes){

        if (requestcode == EXTERNAL) {
            if (grantRes[0] == PackageManager.PERMISSION_GRANTED) {
                photoIntent();
            } else {
                Toast.makeText(this, "Unable to Access Image", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == ATTACH && resultCode == RESULT_OK){
            Uri uri = data.getData();
            System.out.println("sammy_sourceUri "+uri);
            String mimeType = getContentResolver().getType(uri);
            System.out.println("sammy_mimeType "+ mimeType);
            


        }

    }
}

enter image description here

Upvotes: 1

Views: 870

Answers (3)

Prakash Satyani
Prakash Satyani

Reputation: 33

get real path from URI

public String getRealPathFromURI(Uri contentUri) 
{
     String[] proj = { MediaStore.Audio.Media.DATA };
     Cursor cursor = managedQuery(contentUri, proj, null, null, null);
     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
     cursor.moveToFirst();
     return cursor.getString(column_index);
}

FILENAME :

String filename = path.substring(path.lastIndexOf("/")+1);

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006704

I want to get the name and full path so that I can upload the file to server

There is no "full path", because there may not be a "file".

You are invoking ACTION_GET_CONTENT. This returns a Uri to some content. Where that content comes from is up to the developers of the ACTION_GET_CONTENT activity that the user chose. That could be:

  • An ordinary file on the filesystem that happens to be one that you could access
  • An ordinary file on the filesystem that resides somewhere that you cannot access, such as internal storage for the other app
  • A file that requires some sort of conversion for it to be useful, such as decryption
  • A BLOB column in a database
  • Content that is generated on the fly, the way this Web page is generated on the fly by the Stack Overflow servers
  • And so on

To use the content from the Uri, use a ContentResolver and openInputStream().

how to use this InputStream to upload to server API as file?

Either your chosen HTTP API supports an InputStream as the source of this content, or it does not. If it does, just use the InputStream directly. If not, use the InputStream to make a temporary copy of the content as a file that you can directly access (e.g., in getCacheDir()), upload that file, then delete the file when the upload is complete.

Upvotes: 1

Uma Achanta
Uma Achanta

Reputation: 3729

try this

  public static ArrayList<String> getImagesFromCameraDir(Context context) {
        Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ArrayList<String> filePaths = new ArrayList<>();
        final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED};
        Cursor mCursor = context.getContentResolver().query(mImageUri, columns, MediaStore.Images.Media.DATA + " like ? ", new String[]{"%/DCIM/%"}, null);
        if (mCursor != null) {
            mCursor.moveToFirst();

            try {
                int uploadImage = 0;
                uploadImage = mCursor.getCount();
                for (int index = 0; index < uploadImage; index++) {
                    mCursor.moveToPosition(index);
                    int idx = mCursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    filePaths.add(mCursor.getString(idx));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mCursor.close();
            }
        }
        return filePaths;
    }

Upvotes: 0

Related Questions