Android WebView 文件上传

webview文件上传需要重写webchromeclient里面的几个方法:

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.imyuu.travel.utils.SPHelper;

import java.io.File;

/**
 * Created by jiangtao on 2017/5/9 14:04
 * E-mail:[email protected]
 */

public class UploadFileWebChromeClient extends WebChromeClient {
    public ValueCallback uploadMsg;
    public ValueCallback uploadMsgOver5;
    private Activity activity;

    public static final int FILE_CHOOSER_RESULT_CODE = 0x5423;

    @SuppressWarnings("deprecation")
    public UploadFileWebChromeClient(Activity activity) {
        this.activity = activity;
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
    }

    // Android > 5.0
    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
        // TODO 自动生成的方法存根
        uploadMsgOver5 = filePathCallback;
        this.activity.startActivityForResult(createDefaultOpenableIntent(), FILE_CHOOSER_RESULT_CODE);
        return true;
    }

    @SuppressWarnings("static-access")
    public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
        this.uploadMsg = uploadMsg;
        this.activity.startActivityForResult(createDefaultOpenableIntent(), this.FILE_CHOOSER_RESULT_CODE);
    }

    // 3.0 +
    @SuppressWarnings("static-access")
    public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
        this.uploadMsg = uploadMsg;
        this.activity.startActivityForResult(createDefaultOpenableIntent(), this.FILE_CHOOSER_RESULT_CODE);

    }

    // Android < 3.0
    @SuppressWarnings("static-access")
    public void openFileChooser(ValueCallback uploadMsg) {
        this.uploadMsg = uploadMsg;
        this.activity.startActivityForResult(createDefaultOpenableIntent(), this.FILE_CHOOSER_RESULT_CODE);
    }

    private Intent createDefaultOpenableIntent() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        Intent chooser = createChooserIntent(createCameraIntent());
        chooser.putExtra(Intent.EXTRA_INTENT, i);
        return chooser;
    }

    private Intent createChooserIntent(Intent... intents) {
        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
        chooser.putExtra(Intent.EXTRA_TITLE, "选择图片");
        return chooser;
    }

    @SuppressWarnings("static-access")
    private Intent createCameraIntent() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(externalDataDir.getAbsolutePath() + File.separator + ".imyuu");
        cameraDataDir.mkdirs();
        String mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".jpg";
        SPHelper.setParam(this.activity, "cameraImgPath", mCameraFilePath);
        cameraIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
        return cameraIntent;
    }

    public static Uri getImageContentUri(Context context, java.io.File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }
}

然后在对应的activity里面重写onActivityResult方法:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == UploadFileWebChromeClient.FILE_CHOOSER_RESULT_CODE) {
            if (null != uploadFileWebChromeClient.uploadMsg) {
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                if (result == null) {
                    String cameraImgPath = (String) SPHelper.getParam(ChatActivity.this, "cameraImgPath", "");
                    if (cameraImgPath == null) {
                        Logger.e("result1:" + result);
                        uploadFileWebChromeClient.uploadMsg.onReceiveValue(null);
                        uploadFileWebChromeClient.uploadMsg = null;
                        return;
                    }
                    Uri imagePathUri = ImageUtils.createImagePathUri(ChatActivity.this, cameraImgPath);
                    if (imagePathUri != null) {
                        Logger.e("result2:" + imagePathUri);
                        uploadFileWebChromeClient.uploadMsg.onReceiveValue(imagePathUri);
                        uploadFileWebChromeClient.uploadMsg = null;
                    }
                    return;
                }
                Logger.e("result3:" + result);
                uploadFileWebChromeClient.uploadMsg.onReceiveValue(result);
                uploadFileWebChromeClient.uploadMsg = null;
            }
            if (null != uploadFileWebChromeClient.uploadMsgOver5) {
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                if (result == null) {
                    String cameraImgPath = (String) SPHelper.getParam(ChatActivity.this, "cameraImgPath", "");
                    if (cameraImgPath == null) {
                        Logger.e("result4:" + result);
                        uploadFileWebChromeClient.uploadMsgOver5.onReceiveValue(null);
                        uploadFileWebChromeClient.uploadMsgOver5 = null;
                        return;
                    }
                    Uri imagePathUri = ImageUtils.createImagePathUri(ChatActivity.this, cameraImgPath);
                    if (imagePathUri != null) {
                        Logger.e("result5:" + imagePathUri);
                        uploadFileWebChromeClient.uploadMsgOver5.onReceiveValue(new Uri[]{imagePathUri});
                        uploadFileWebChromeClient.uploadMsgOver5 = null;
                    }
                    return;
                }
                Logger.e("result6:" + result);
                uploadFileWebChromeClient.uploadMsgOver5.onReceiveValue(new Uri[]{result});
                uploadFileWebChromeClient.uploadMsgOver5 = null;
            }
        }
    }

其中SPHelper是sharepreference的封装类:

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by jiangtao on 2016/12/25 12:22
 * E-mail:[email protected]
 */

public class SPHelper {
    /**
     * 保存在手机里面的文件名
     */
    private static final String FILE_NAME = "share_date";


    /**
     * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
     *
     * @param context
     * @param key
     * @param object
     */
    public static void setParam(Context context, String key, Object object) {

        String type = object.getClass().getSimpleName();
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if ("String".equals(type)) {
            editor.putString(key, (String) object);
        } else if ("Integer".equals(type)) {
            editor.putInt(key, (Integer) object);
        } else if ("Boolean".equals(type)) {
            editor.putBoolean(key, (Boolean) object);
        } else if ("Float".equals(type)) {
            editor.putFloat(key, (Float) object);
        } else if ("Long".equals(type)) {
            editor.putLong(key, (Long) object);
        }

        editor.apply();
    }


    /**
     * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
     *
     * @param context
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object getParam(Context context, String key, Object defaultObject) {
        String type = defaultObject.getClass().getSimpleName();
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);

        if ("String".equals(type)) {
            return sp.getString(key, (String) defaultObject);
        } else if ("Integer".equals(type)) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if ("Boolean".equals(type)) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if ("Float".equals(type)) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if ("Long".equals(type)) {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }
}

createImagePathUri是创建本地文件的Uri:

/**
     * 创建一条图片地址uri,用于保存拍照后的照片
     *
     * @param context
     * @return 图片的uri
     */
    public static Uri createImagePathUri(Context context,String path) {
        Uri imageFilePath;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        Logger.e("SDK:" + Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            imageFilePath = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        } else {
            imageFilePath = Uri.fromFile(new File(path));
        }
        return imageFilePath;
    }

你可能感兴趣的:(Android WebView 文件上传)