11
Uri = content://com.whatsapp.provider.media/item/118727

I'm not able to get the actual path from this URI

11
  • image path? what do you need it for? if for ImageView, then simply use setImageURI method
    – pskink
    Nov 3, 2017 at 8:13
  • i need to upload into server Nov 3, 2017 at 10:21
  • so you dont need any path, what you need is InputStream - see ContentResolver API docs on how to get one
    – pskink
    Nov 3, 2017 at 10:23
  • Ohh. will try it and revert u. Thanks.. Nov 3, 2017 at 10:27
  • it will download the image again and upload?? Nov 3, 2017 at 10:28

2 Answers 2

4

Following the Documentation , i receive the image intent through :

void onCreate (Bundle savedInstanceState) {
    ...
    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if (type.startsWith("image/")) {
            handleSendImage(intent); // Handle single image being sent
        }
    } 
}

ContentResolver wasn't working in this case as "_data" field was returning null. So i found another way to get a file from content URI.

In handleSendImage() you need to open inputStream and then copy it into a file.

void handleSendImage(Intent intent) throws IOException {
    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
    if (imageUri != null) {
      File file = new File(getCacheDir(), "image");
      InputStream inputStream=getContentResolver().openInputStream(imageUri);
      try {

        OutputStream output = new FileOutputStream(file);
        try {
          byte[] buffer = new byte[4 * 1024]; // or other buffer size
          int read;

          while ((read = inputStream.read(buffer)) != -1) {
            output.write(buffer, 0, read);
          }

          output.flush();
        } finally {
          output.close();
        }
      } finally {
        inputStream.close();
        byte[] bytes =getFileFromPath(file);
        //Upload Bytes.
      }
    }
  }

getFileFromPath() gets you the bytes which you can upload on your server.

  public static byte[] getFileFromPath(File file) {
    int size = (int) file.length();
    byte[] bytes = new byte[size];
    try {
      BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
      buf.read(bytes, 0, bytes.length);
      buf.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return bytes;
  }
2
  • @Suseendran Kandasamy : Did you try this one ?
    – Anonymous
    Apr 2, 2018 at 10:17
  • i want to know something, how can i know the extension of the old file after getting it from contentResolver? Thanks! May 29, 2019 at 12:58
0

You can get imageFilePath from getRealPathFromUri() below:

String filePath = getRealPathFromUri(this, fileUri);

   // You can upload it as File 
   if (filePath != null && !filePath.isEmpty()) {
        File file = new File(filePath);
        if (file.exists()) {
        // Using Retrofit you can do it like

        // create Retrofit Client code......

        // creates RequestBody instance from file
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        // MultipartBody.Part is used to send also the actual filename
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

       // pass body as parameter while execute call

       }
   }

getRealPathFromUri()

public static String getRealPathFromUri(Context context, final Uri uri) {
        // DocumentProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    private static String getDataColumn(Context context, Uri uri, String selection,
                                 String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
1
  • 1
    Its not working for whatsapp content://com.whatsapp.provider.media/item/118727 Mar 27, 2018 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.