How I can get the mime type of a file having its Uri?

前端 未结 4 1320
南旧
南旧 2020-12-12 12:22

I have a List of Uris obtained with the Gallery and the Camera. These Uris are like this: content://media/external/images/media/94. How I can get its mime type?

相关标签:
4条回答
  • 2020-12-12 12:52

    You can try

    ContentResolver cR = context.getContentResolver();
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String type = mime.getExtensionFromMimeType(cR.getType(uri));
    

    Edit :

    mime.getExtensionFromMimeType(cR.getType(uri)) 
    

    returns -> "jpeg"

    cR.getType(uri);
    

    returns "image/jpeg" that is the expected value.

    0 讨论(0)
  • 2020-12-12 12:52

    for Content Uri.

    ContentResolver cr = context.getContentResolver();
    mimeType = cr.getType(contentUri);
    

    for File Uri.

    String fileExtension = MimeTypeMap.getFileExtensionFromUrl(fileUri
                .toString());
    mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                fileExtension.toLowerCase());
    

    for Both, works for Content as well as File.

    public String getMimeType(Context context, Uri uri) {
        String mimeType = null;
        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            ContentResolver cr = context.getContentResolver();
            mimeType = cr.getType(uri);
        } else {
            String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                    .toString());
            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                    fileExtension.toLowerCase());
        }
        return mimeType;
    }
    
    0 讨论(0)
  • 2020-12-12 12:55

    Instead of this:

    String type = mime.getExtensionFromMimeType(cR.getType(uri));
    

    Do this:

    String type = cR.getType(uri);
    

    And you will get this: image/jpeg.

    0 讨论(0)
  • 2020-12-12 13:11

    This method returns the extension of the file (jpg, png, pdf, epub etc..).

     public static String getMimeType(Context context, Uri uri) {
        String extension;
    
        //Check uri format to avoid null
        if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //If scheme is a content
            final MimeTypeMap mime = MimeTypeMap.getSingleton();
            extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
        } else {
            //If scheme is a File
            //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
            extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
    
        }
    
        return extension;
    }
    
    0 讨论(0)
提交回复
热议问题