Convert mime types in fileChooserParams to the right format for Intent.setType

前端 未结 2 649
生来不讨喜
生来不讨喜 2020-12-16 07:13

I am trying to upload a file using a WebView in Android.

This is the code in use:

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean o         


        
相关标签:
2条回答
  • 2020-12-16 07:57

    I resolved simply adding the following 2 lines in my PR:

    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_MIME_TYPES, fileChooserParams.getAcceptTypes());
    

    Outcome:

    2019-04-01 00:18:00.501 32500-32500/my.app.bundle.id D/SystemWebChromeClient: : fileChooserParams.getAcceptTypes(): [.jpg,.png,.tiff,.jpeg,.tif,.pdf]

    2019-04-01 00:18:00.503 2225-2921/system_process I/ActivityManager: START u0 {act=android.intent.action.GET_CONTENT cat=[android.intent.category.OPENABLE] typ=image/* cmp=com.android.documentsui/.picker.PickActivity (has extras)} from uid 10105

    I hope it will get accepted.

    0 讨论(0)
  • 2020-12-16 08:18

    I improved the solution using this code:

       // Validation utility for mime types
        private List<String> extractValidMimeTypes(String[] mimeTypes) {
            List<String> results = new ArrayList<String>();
            List<String> mimes;
            if (mimeTypes.length() == 1 && mimeTypes[0].contains(",")) {
                mimes = Arrays.asList(mimeTypes[0].split(","));
            } else {
                mimes = Arrays.asList(mimeTypes);
            }
            MimeTypeMap mtm = MimeTypeMap.getSingleton();
            for (String mime : mimes) {
                if (mime != null && mime.trim().startsWith(".")) {
                    String extensionWithoutDot = mime.trim().substring(1, mime.trim().length());
                    String derivedMime = mtm.getMimeTypeFromExtension(extensionWithoutDot);
                    if (derivedMime != null && !results.contains(derivedMime)) {
                        // adds valid mime type derived from the file extension
                        results.add(derivedMime);
                    }
                } else if (mtm.getExtensionFromMimeType(mime) != null && !results.contains(mime)) {
                    // adds valid mime type checked agains file extensions mappings
                    results.add(mime);
                }
            }
            return results;
        }
    
    
    public boolean onShowFileChooser(WebView webView, final ValueCallback<Uri[]> filePathsCallback, final WebChromeClient.FileChooserParams fileChooserParams) {
        Intent intent = fileChooserParams.createIntent();
        List<String> validMimeTypes = extractValidMimeTypes(fileChooserParams.getAcceptTypes());
        if (validMimeTypes.isEmpty()) {
            intent.setType(DEFAULT_MIME_TYPE);
        } else {
            intent.setType(String.join(" ", validMimeTypes));
        }
        ...
    

    See my Pull Request for more details.

    0 讨论(0)
提交回复
热议问题