Search code examples
androidmediastorestorage-access-framework

Get FIle extension using Android Storage Access Framework


I am using the Storage Access Framework in android for selecting images and uploading in my app. Before uploading these images to my server, i also process these images (resizing). However, in the URI returned by the SAF, there is no extension appended, i don't know how to get extension of the file. I need to differentiate between png and jpeg. How can i achieve that ? Example uri returned from SAF - content://com.android.providers.media.documents/document/image%3A245309

My code is something like this


if (resultData != null) {
                        final ClipData clipData = resultData.getClipData();
                        int takeFlags = resultData.getFlags();
                        takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        ArrayList<Uri> uris = new ArrayList<Uri>();
                        if(clipData != null){
                            for (int i = 0; i < clipData.getItemCount(); i++) {
                                ClipData.Item item = clipData.getItemAt(i);
                                Uri dataUri = item.getUri();
                                if (dataUri != null) {
                                    uris.add(dataUri);
                                    Log.d(TAG, "File URI : " + dataUri.toString());
                                }
                            }
                        }else{
                            Uri dataUri = resultData.getData();
                            if (dataUri != null) {
                                uris.add(dataUri);
                            }
                        }
                        processFiles(uris);
                }

Solution

  • I need to differentiate between png and jpeg. How can i achieve that ?

    Call getType() on a ContentResolver, passing in the Uri. This will return the MIME type associated with the content, such as image/png.