Webview 支持文件上傳


默認情況下情況下, 在一個帶有input tpye=file標簽的Html頁面, 使用 Android的WebView是不能夠支持上傳文件的 (在iOS和微信上完全正常工作) 。而這個,也是在我們的前端工程師告知之后才了解的。因為Android的每個版本WebView的實現有差異,因此需要對不同版本去適配。

主要思路是重寫WebChromeClient,然后在Activity中接收選擇到的文件Uri,傳給頁面去上傳就可以了。

由於不同版本的差別,Android 5.0以下的版本,ValueCallback 的onReceiveValue接收的參數類型是 Uri, 5.0及以上版本接收的是 Uri數組,在傳值的時候需要注意。
選擇文件會使用系統提供的組件或者其他支持的app,返回的uri有的直接是文件的url,有的是contentprovider的uri,因此我們需要統一處理一下,轉成文件的uri。
調用getPath可以將Uri轉成真實文件的Path,然后可以自己生成文件的Uri

WebView設置WebChromeClient

重寫WebChromeClient中關於文件選擇的方法,onShowFileChooser和openFileChooser。(項目中只需要選擇圖片,所以加上了圖片過濾。)
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        // android 5.0 這里需要使用android5.0 sdk
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null) mFilePathCallback.onReceiveValue(null);
            mFilePathCallback = filePathCallback;
            /** 
            Open Declaration   String android.provider.MediaStore.ACTION_IMAGE_CAPTURE = "android.media.action.IMAGE_CAPTURE" 
            Standard Intent action that can be sent to have the camera application capture an image and return it.  
            The caller may pass an extra EXTRA_OUTPUT to control where this image will be written.
             If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field. 
             This is useful for applications that only need a small image. 
             If the EXTRA_OUTPUT is present, then the full-sized image will be written to the Uri value of EXTRA_OUTPUT. 
             As of android.os.Build.VERSION_CODES.LOLLIPOP, this uri can also be supplied through android.content.Intent.setClipData(ClipData).
             If using this approach, you still must supply the uri through the EXTRA_OUTPUT field for compatibility with old applications.
             If you don't set a ClipData, it will be copied there for you when calling Context.startActivity(Intent). 
            See Also:EXTRA_OUTPUT 
            標准意圖,被發送到相機應用程序捕獲一個圖像,並返回它。通過一個額外的extra_output控制這個圖像將被寫入。如果extra_output是不存在的, 
            那么一個小尺寸的圖像作為位圖對象返回。如果extra_output是存在的,那么全尺寸的圖像將被寫入extra_output URI值。 
             */
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                File photoFile = null;// Create the File where the photo should go  
                try {
                    //設置MediaStore.EXTRA_OUTPUT路徑,相機拍照寫入的全路徑  
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath"mCameraPhotoPath);
                } catch (Exception ex) {
                    // Error occurred while creating the File 
                    Log.e("WebViewSetting""Unable to create Image File", ex);
                }
                // Continue only if the File was successfully created  
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    System.out.println(mCameraPhotoPath);
                } else {
                    takePictureIntent = null;
                }
            }
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");
            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
                System.out.println(takePictureIntent);
            } else {
                intentArray = new Intent[0];
            }
            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE"Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
            return true;
        }
        //The undocumented magic method override  
        //Eclipse will swear at you if you try to put @Override here  
        // For Android 3.0+  
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            Log.d("bqt""openFileChooser1");
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            WebViewActivity.this.startActivityForResult(Intent.createChooser(i, "Image Chooser")FILECHOOSER_RESULTCODE);
        }
        // For Android 3.0+  
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            Log.d("bqt""openFileChooser2");
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            WebViewActivity.this.startActivityForResult(Intent.createChooser(i, "Image Chooser")FILECHOOSER_RESULTCODE);
        }
        //For Android 4.1  
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            Log.d("bqt""openFileChooser3");
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            WebViewActivity.this.startActivityForResult(Intent.createChooser(i, "Image Chooser"), WebViewActivity.FILECHOOSER_RESULTCODE);
        }
    };

選擇結果的回調

在onActivityResult中獲取對應的選取文件的返回結果
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (result != null) {
                String imagePath = ImageFilePath.getPath(this, result);
                if (!TextUtils.isEmpty(imagePath)) result = Uri.parse("file:///" + imagePath);
            }
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        } else if (requestCode == INPUT_FILE_REQUEST_CODE && mFilePathCallback != null) {
            // 5.0的回調  
            Uri[] results = null;
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    // If there is not data, then we may have taken a photo  
                    if (mCameraPhotoPath != null) results = new Uri[] { Uri.parse(mCameraPhotoPath) };
                } else {
                    String dataString = data.getDataString();
                    if (dataString != null) results = new Uri[] { Uri.parse(dataString) };
                }
            }
            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

文件路徑的獲取

返回文件的解析,因為html頁面需要的是文件,所以客戶端需要返回的是對應文件的路徑。這樣,就會存在一個問題,在Android 4.4上,通過文件選擇返回的結果都是對應以content開頭格式的對應的路徑。這就得需要咱們來進行判斷,最終都需要轉回成以file開頭對應的格式文件。下面,我封裝成了一個ImageFilePath的類,通過調用getPath方法來獲取最終的結果。這個類的方法如下:
public class ImageFilePath {
    /**
    * Method for return file path of Gallery image
    */
    public static String getPath(final Context context, final Uri uri) {
        // check here to KITKAT or new version
        boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                String id = DocumentsContract.getDocumentId(uri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, nullnull);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                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;
                String selection = "_id=?";
                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, nullnull);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) return uri.getPath();
        return null;
    }
    /**
     * Get the value of the data column for this Uri. This is useful for MediaStore Uris, and other file-based ContentProviders.
     * @param context   The context.
     * @param uri The Uri to query.
     * @param selection   (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = "_data";
        String[] projection = { column };
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) cursor.close();
        }
        return null;
    }
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}





附件列表

     


    免責聲明!

    本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



     
    粵ICP備18138465號   © 2018-2025 CODEPRJ.COM