简体   繁体   中英

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

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 .

Using Simple Storage is much easier:

MediaFile file = new MediaFile(context, uri);
String extension = file.getExtension();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM