让Android的WebView支持html里面的文件上传

默认情况下,Android的webview是不支持<input type=file>的,点击没有任何反应,如果希望点击上传,弹出选择文件、图片的窗口,那就需要自定义一个WebChromeClient

public class MyChromeClient extends WebChromeClient {
    public ValueCallback<Uri> UploadMsg;
    public ValueCallback<Uri[]> UploadMsg2;
    private Activity activity;

    public static final int FILECHOOSER_RESULTCODE = 5173;

    public static String mCameraFilePath = "";

    @SuppressWarnings("deprecation")
    public MyChromeClient(Activity cordova) {

        this.activity = cordova;

    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {

        super.onProgressChanged(view, newProgress);

    }

    // <input type="file" name="fileField" id="fileField" />

    // Android > 4.1.1

    @Override
    public boolean onShowFileChooser(WebView webView,
            ValueCallback<Uri[]> filePathCallback,
            FileChooserParams fileChooserParams) {
        // TODO 自动生成的方法存根
        UploadMsg2 = filePathCallback;
        this.activity.startActivityForResult(createDefaultOpenableIntent(),

                this.FILECHOOSER_RESULTCODE);
        return false;
    }

    @SuppressWarnings("static-access")
    public void openFileChooser(ValueCallback<Uri> uploadMsg,

    String acceptType, String capture) {

        UploadMsg = uploadMsg;

        this.activity.startActivityForResult(createDefaultOpenableIntent(),

        this.FILECHOOSER_RESULTCODE);

    }

    // 3.0 +

    @SuppressWarnings("static-access")
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {

        UploadMsg = uploadMsg;

        this.activity.startActivityForResult(createDefaultOpenableIntent(),

        this.FILECHOOSER_RESULTCODE);

    }

    // Android < 3.0

    @SuppressWarnings("static-access")
    public void openFileChooser(ValueCallback<Uri> uploadMsg) {

        UploadMsg = uploadMsg;

        this.activity.startActivityForResult(createDefaultOpenableIntent(),

        this.FILECHOOSER_RESULTCODE);

    }

    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()/*
                                                                 *
                                                                 * ,
                                                                 *
                                                                 * createCamcorderIntent
                                                                 *
                                                                 * (),
                                                                 *
                                                                 * createSoundRecorderIntent
                                                                 *
                                                                 * ()
                                                                 */);

        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 + "515aaa");

        cameraDataDir.mkdirs();

        String mCameraFilePath = cameraDataDir.getAbsolutePath()

        + File.separator + System.currentTimeMillis() + ".jpg";

        this.mCameraFilePath = mCameraFilePath;

        cameraIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);

        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,

        Uri.fromFile(new File(mCameraFilePath)));

        return cameraIntent;

    }

    /*
     *
     * private Intent createCamcorderIntent() { return new
     *
     * Intent(MediaStore.ACTION_VIDEO_CAPTURE); }
     *
     *
     *
     * private Intent createSoundRecorderIntent() { return new
     *
     * Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION); }
     */

    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;

            }

        }

    }

}

然后指定webview使用这个client

webview.setWebChromeClient( new MyChromeClient (this));
时间: 2024-08-03 20:47:26

让Android的WebView支持html里面的文件上传的相关文章

android 在webview中填充网站的文件上传的文件路径

网站中有一个编辑框,要求输入上传的文件路径,如果需要自动填充, 不能 使用: webView.loadUrl("javascript:setPhoto('"+ Uri.fromFile(new File(com.yiheng.xmb.Constant.PHOTOIMAGECROP)) + "')"); 和 javascript:setPhoto('/mnt/sdcard/fffff') 可以使用:ContentProvide 把这个"content://y

Android与Asp.Net Web服务器的文件上传下载BUG汇总【更新】

遇到的问题: 1.java.io.IOException: open failed: EINVAL (Invalid argument)异常,在模拟器中的sd卡创建文件夹和文件时报错 出错原因可能是:(1)文件名称中含有不符合规范的字符,比如“:”,“?”或者空格等.(2)需要先创建文件夹目录再创建文件,不能直接创建文件. 2. android.os.NetworkOnMainThreadException异常,从服务器请求数据后,写入文件时报错 出错原因:在主线程内执行了访问http的操作,最

在Android浏览器中通过WebView调用相机拍照/选择文件 上传到服务器

最近做的一个项目中,有这样一个要求,在浏览器中调用系统的拍照功能或者选择文件,然后将文件上传到服务器,类似修改头像.        简单而言,就是在一个html页面中有这样一段代码 <input class="filePrew" type="file" capture="camera" accept="image/*" name="image"> 刚开始的时候,没有感觉很难的,因为在UC浏览器.

Android volley 解析(三)之文件上传篇

前面我们讲了如何通过 volley 实现表单的提交,而这篇文章跟上一篇衔接很大,如果没有看上一篇 blog 的朋友,建议先去看看 Android Volley解析(二)之表单提交篇 因为文件上传实质就是表单的提交,只不过它提交的数据包含文件类型,接下来还是按照表单提交的套路来分析. 数据格式 这里我们通过图片上传的案例来分析,其他文件也是同样的实现方式:以下是我在传图网传图时,上传的数据格式,先来分析一下 POST http://chuantu.biz/upload.php HTTP/1.1 H

android开发里跳过的坑——图片文件上传失败

使用的apache的httpclient的jar包,做的http图片上传,上传时,服务器总返文件格式不对.后来发现,是由于在创建FileBody时,使用了默认的ContentType引起的.所以服务器有判断文件类型的要求的时候,创建FlieBody时需要注意添加MIME类型,例如PNG图片文件: new FileBody(entity.getValue(), ContentType.create("IMAGE/PNG")));

android批量文件上传(android批量图片上传)

项目中多处用到文件批量上传功能,今天正好解决了此问题,在此写出来,以便日后借鉴. 首先,以下架构下的批量文件上传可能会失败或者不会成功: 1.android客户端+springMVC服务端:服务端采用org.springframework.web.multipart.MultipartHttpServletRequest作为批量上传接收类,这种搭配下的批量文件上传会失败,最终服务端只会接受到一个文件,即只会接受到第一个文件.可能因为MultipartHttpServletRequest对serv

考虑浏览器兼容的文件上传(IE8不支持FormData)

方法一:使用FormData(因IE8不支持FormData, IE10才支持,因此此方法不兼容IE10以下的IE浏览器) 也可参考文章 http://www.jianshu.com/p/46e6e03a0d53 html: <input type="file" class="form-control" id="inputfile" title="多个文件请打包后再上传" style="display:inli

Android WebView 支持 文件上传(Html File Upload)

背景:有个html页面,用html里面自带的<input type =file/>上传文件(图片,word,Excel等)浏览器直接打开可以上传,套壳在Android app里面,点击文件上传没反应,修改Android代码,可以实现相应功能,亲测有效. 1.在oncreate 方法上面 加入以下代码: 1 private static final int REQUEST_STORAGE = 1; 2 private static final int REQUEST_LOCATION = 2;

webview 不支持文件上传 &lt;input type=&quot;file&quot; /&gt;

项目中遇到文件上传的需求,IOS直接是支持的,安卓端却没反应,有些机型甚至闪退. 找了很多原因,在网上找的办法,实测可行,做个记录,知识分享. Html文件上传 <input type="file" class="uploadBtn" multiple="multiple" accept="image/jpeg"> 手机端WebView重写方法 // 1.设置WebChromeClient,重写文件上传回调 mWe