Android WebView 上傳文件支持全解析
默認(rèn)情況下情況下,使用Android的WebView是不能夠支持上傳文件的。而這個,也是在我們的前端工程師告知之后才了解的。因為Android的每個版本W(wǎng)ebView的實現(xiàn)有差異,因此需要對不同版本去適配?;艘稽c時間,參考別人的代碼,這個問題已經(jīng)解決,這里把我踩過的坑分享出來。
主要思路是重寫WebChromeClient,然后在WebViewActivity中接收選擇到的文件Uri,傳給頁面去上傳就可以了。
創(chuàng)建一個WebViewActivity的內(nèi)部類
public class XHSWebChromeClient extends WebChromeClient {
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
CLog.i("UPFILE", "in openFile Uri Callback");
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
}
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
CLog.i("UPFILE", "in openFile Uri Callback has accept Type" + acceptType);
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
}
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
i.setType(type);
startActivityForResult(Intent.createChooser(i, "File Chooser"),
FILECHOOSER_RESULTCODE);
}
// For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
CLog.i("UPFILE", "in openFile Uri Callback has accept Type" + acceptType + "has capture" + capture);
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
}
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
i.setType(type);
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
//Android 5.0+
@Override
@SuppressLint("NewApi")
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
}
CLog.i("UPFILE", "file chooser params:" + fileChooserParams.toString());
mUploadMessage = filePathCallback;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null
&& fileChooserParams.getAcceptTypes().length > 0) {
i.setType(fileChooserParams.getAcceptTypes()[0]);
} else {
i.setType("*/*");
}
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
return true;
}
}
上面openFileChooser是系統(tǒng)未暴露的接口,因此不需要加Override的注解,同時不同版本有不同的參數(shù),其中的參數(shù),第一個ValueCallback用于我們在選擇完文件后,接收文件回調(diào)到網(wǎng)頁內(nèi)處理,acceptType為接受的文件mime type。在Android 5.0之后,系統(tǒng)提供了onShowFileChooser來讓我們實現(xiàn)選擇文件的方法,仍然有ValueCallback,在FileChooserParams參數(shù)中,同樣包括acceptType。我們可以根據(jù)acceptType,來打開系統(tǒng)的或者我們自己創(chuàng)建文件選擇器。當(dāng)然如果需要打開相機(jī)拍照,也可以自己去使用打開相機(jī)拍照的Intent去打開即可。
處理選擇的文件
以上是打開響應(yīng)的選擇文件的界面,我們還需要處理接收到文件之后,傳給網(wǎng)頁來響應(yīng)。因為我們前面是使用startActivityForResult來打開的選擇頁面,我們會在onActivityResult中接收到選擇的結(jié)果。Show code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage) return;
Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
if (result == null) {
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
return;
}
CLog.i("UPFILE", "onActivityResult" + result.toString());
String path = FileUtils.getPath(this, result);
if (TextUtils.isEmpty(path)) {
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
return;
}
Uri uri = Uri.fromFile(new File(path));
CLog.i("UPFILE", "onActivityResult after parser uri:" + uri.toString());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mUploadMessage.onReceiveValue(new Uri[]{uri});
} else {
mUploadMessage.onReceiveValue(uri);
}
mUploadMessage = null;
}
}
以上代碼主要就是調(diào)用ValueCallback的onReceiveValue方法,將結(jié)果傳回web。
注意,其他要說的,重要
由于不同版本的差別,Android 5.0以下的版本,ValueCallback 的onReceiveValue接收的參數(shù)類型是Uri, 5.0及以上版本接收的是Uri數(shù)組,在傳值的時候需要注意。
選擇文件會使用系統(tǒng)提供的組件或者其他支持的app,返回的uri有的直接是文件的url,有的是contentprovider的uri,因此我們需要統(tǒng)一處理一下,轉(zhuǎn)成文件的uri,可參考以下代碼(獲取文件的路徑)。
調(diào)用getPath可以將Uri轉(zhuǎn)成真實文件的Path,然后可以自己生成文件的Uri
public class FileUtils {
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* 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;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final 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;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
}
再有,即使獲取的結(jié)果為null,也要傳給web,即直接調(diào)用mUploadMessage.onReceiveValue(null),否則網(wǎng)頁會阻塞。
最后,在打release包的時候,因為我們會混淆,要特別設(shè)置不要混淆WebChromeClient子類里面的openFileChooser方法,由于不是繼承的方法,所以默認(rèn)會被混淆,然后就無法選擇文件了。
就這樣吧。
原文地址:http://blog.isming.me/2015/12/21/android-webview-upload-file/
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android retrofit上傳文件實例(包含頭像)
- Android OkHttp Post上傳文件并且攜帶參數(shù)實例詳解
- android 上傳文件到服務(wù)器代碼實例
- Android實現(xiàn)上傳文件功能的方法
- Android中實現(xiàn)OkHttp上傳文件到服務(wù)器并帶進(jìn)度
- Android實現(xiàn)上傳文件到服務(wù)器實例詳解
- Android上傳文件到服務(wù)端并顯示進(jìn)度條
- android 開發(fā)中使用okhttp上傳文件到服務(wù)器
- Android上傳文件到服務(wù)器的方法
- Android程序開發(fā)通過HttpURLConnection上傳文件到服務(wù)器
- Android使用Retrofit上傳文件功能
相關(guān)文章
Android Service判斷設(shè)備聯(lián)網(wǎng)狀態(tài)詳解
本文主要介紹Android Service判斷聯(lián)網(wǎng)狀態(tài),這里提供了相關(guān)資料并附有示例代碼,有興趣的小伙伴可以參考下,幫助開發(fā)相關(guān)應(yīng)用功能2016-08-08
Android自定義view實現(xiàn)圓形與半圓形菜單
這篇文章主要介紹了Android自定義view實現(xiàn)圓形與半圓形菜單的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11
Android開發(fā)之開發(fā)者頭條(一)啟動頁實現(xiàn)
這篇文章主要介紹了Android開發(fā)之開發(fā)者頭條(一)啟動頁實現(xiàn)的相關(guān)資料,需要的朋友可以參考下2016-04-04
Android開發(fā)實現(xiàn)標(biāo)題隨scrollview滑動變色的方法詳解
這篇文章主要介紹了Android開發(fā)實現(xiàn)標(biāo)題隨scrollview滑動變色的方法,涉及Android針對滑動事件的響應(yīng)、界面布局、屬性動態(tài)變換等相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
Android基于TextView不獲取焦點實現(xiàn)跑馬燈效果
這篇文章主要介紹了Android基于TextView不獲取焦點實現(xiàn)跑馬燈效果,結(jié)合實例形式分析了Android基于TextView實現(xiàn)跑馬燈的功能與布局相關(guān)技巧,需要的朋友可以參考下2017-02-02
android不同activity之間共享數(shù)據(jù)解決方法
最近做局域網(wǎng)socket連接問題,要在多個activity之間公用一個socket連接,就在網(wǎng)上搜了下資料,感覺還是application方法好用,帖出來需要的朋友可以參考下2012-11-11
Android實現(xiàn)動態(tài)切換組件背景的方法
這篇文章主要介紹了Android實現(xiàn)動態(tài)切換組件背景的方法,需要的朋友可以參考下2014-07-07

