-4

we want to choose a pdf file using intent from a gallery so how can get a real path of a pdf file. We want to choose a PDF file from a gallery and upload this file on a server.

Ronak Thakkar
  • 2,515
  • 6
  • 31
  • 45
thakur neha
  • 11
  • 1
  • 5

2 Answers2

0
public String getPathFromURI(Context context, Uri contentUri) {
if ( contentUri.toString().indexOf("file:///") > -1 ){
    return contentUri.getPath();
}

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();
      }
}

}

0

Hi here is sample code for selecting pdf file from external storage and get file's path using which you can access file's data and upload data on your server.

Here PICK_IMAGE is any number you want as your request code.

                 Intent intent = new Intent();
                    intent.setType("application/pdf");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select File"),PICK_IMAGE);
 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);


    if (requestCode == PICK_IMAGE) {

        try {

            Uri uri1 = data.getData();
            String path = String.valueOf(uri1);
            String path_lastPart = path.substring(path.indexOf("/storage"));


            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                // Do the file write

                path_lastPart = path_lastPart.replace("%20", " ");
                File yourFile = new File(path_lastPart);


            } else {
                // Request permission from the user

               ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
            }

        } catch (Exception e2) {

            Log.e("macro", "" + e2);
        }
    }



}
Vrushi Patel
  • 2,361
  • 1
  • 17
  • 30