如何将捕获的图像从相机上传到网页浏览

时间:2018-02-19 15:59:14

标签: android webview android-webview android-camera jfilechooser

我有这个html,如果我用chrome应用程序打开它,让用户用相机拍照并上传它,效果很好。选择相机拍摄的照片后,将显示文件名称,使用提交按钮我可以上传照片。

<html>
<body>    
<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" accept="image/*"   name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>    
</body>
</html>

问题是,如果我在Android应用程序的webview上打开这个网站,那么,相机是打开的,是的,但是在接受了捕获的图像之后,那么,图像没有被传递给html,并且可以上传它。正在显示“没有文件选择”消息。

这是我的webview对象的源代码:

        webView=new WebView(ctx);           
        webView.loadUrl(URLParser.parse(this.url));

        webView.getLayoutParams().height=LinearLayout.LayoutParams.MATCH_PARENT;
        webView.getLayoutParams().width=LinearLayout.LayoutParams.MATCH_PARENT;
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webView.getSettings().setJavaScriptEnabled(allowJavascript);
        webView.getSettings().setSupportZoom(allowZooming); 
        webView.getSettings().setBuiltInZoomControls(allowZooming);
        CookieManager.getInstance().setAcceptCookie(allowCookies);

        webView.setDownloadListener(new DownloadListener() {
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse( url ));                
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ApplicationContextProvider.getContext().startActivity(i);
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            public void onGeolocationPermissionsShowPrompt(String origin, android.webkit.GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg, WebChromeClient.FileChooserParams fileChooserParams){

                // Store all the mime types in an array
                String inputAcceptParameter = fileChooserParams.getAcceptTypes()[0];
                String[] mimeTypes = inputAcceptParameter.split(",");
                boolean isImage = false;
                for(String mimeType : mimeTypes) {
                    if(mimeTypes[0].equals("image/*"))
                        isImage = true;
                }

                uploadMsgCopy = uploadMsg;

                if(isImage) {
                    Util.launchExternalCameraGalleryChooserApp(Constants.WEB_INPUT);
                } else {
                    Util.launchExternalBrowser(Constants.WEB_INPUT);
                }

                return true;
            }

        });

        webView.setWebViewClient(new WebViewClient(){
            boolean isFirstLoad = true;

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if(AdManager.getInstance().hasAds() && isFirstLoad == false && AdManager.getInstance().interstitialIntervalExceeded())
                    AdManager.getInstance().showInterstitial(ctx);
                isFirstLoad = false;
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {                         
                if( url.startsWith("browser:") ){
                    launchBrowser( url.substring(8));
                }else if( url.startsWith("market:") || url.endsWith(".pdf")){
                    launchBrowser( url );
                }else if( url.startsWith("https://www.google.com/maps/") || url.startsWith("http://maps.google") || url.startsWith("https://maps.google")){
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        SectionManager.getInstance().getCurrentActivity().startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else if (url.startsWith("tel:")) {
                    try {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url)); 
                        SectionManager.getInstance().getCurrentActivity().startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else if(url.startsWith("mailto:")){
                    MailTo mt = MailTo.parse(url);
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_EMAIL, new String[] { mt.getTo() });
                    intent.putExtra(Intent.EXTRA_TEXT, mt.getBody());
                    intent.putExtra(Intent.EXTRA_SUBJECT, mt.getSubject());
                    intent.putExtra(Intent.EXTRA_CC, mt.getCc());
                    intent.setType("message/rfc822");
                    SectionManager.getInstance().getCurrentActivity().startActivity(intent);                
                }
                return true;
            }               

            //This method launches the phone's Internet browser with the URL passed as parameter
            //@param url            
            private void launchBrowser( String url ){
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse( url ));                
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ApplicationContextProvider.getContext().startActivity(i);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                Toast toast = Toast.makeText(SectionManager.getInstance().getCurrentActivity(), R.string.SSL_ERROR, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                String webUrl = webView.getUrl();
                // This if solve a bug with (Facebook plugins for web pages) like buttons or comments
                if (url.startsWith("https://m.facebook.com/plugins/close_popup.php")) {
                    view.goBack();
                    return;
                }
                super.onPageFinished(view, webUrl);
            }
        });     

这是启动相机的方法:

    /**
     * Launch an selection of all available ACTION_PICK "gallery" intents (external APP) to select an file.
     * Also add the IMAGE_CAPTURE "camera" intent to selection if the device has an camera.
     * If they don't have an APP of type ACTION_PICK, they try to launch an APP of type IMAGE_CAPTURE
     * @param onActivityResultCode the result code returned to onActivityResult when the intent has finish his job
     */
public static void launchExternalCameraGalleryChooserApp(int onActivityResultCode){

    Activity activity = SectionManager.getInstance().getCurrentActivity();

    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    Intent takePictureIntent =  new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


    if(galleryIntent.resolveActivity( activity.getPackageManager()) != null ) {

        Intent[] intentArray = new Intent[0];
        if(takePictureIntent.resolveActivity( activity.getPackageManager()) != null ){
            intentArray = new Intent[] { takePictureIntent };
        }

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, galleryIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
        activity.startActivityForResult(chooserIntent, onActivityResultCode);

    } else if(takePictureIntent.resolveActivity( activity.getPackageManager()) != null ) {

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, galleryIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Camera Chooser");
        activity.startActivityForResult(takePictureIntent, onActivityResultCode);

    }
}

这是我的onActivityResult方法的来源:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    switch (requestCode){
        case Constants.WEB_INPUT:
            if(Build.VERSION.SDK_INT >= 21) {
                Uri[] results = null;
                if (resultCode == Activity.RESULT_OK) { //&& intent != null
                    if (uploadMsgCopy == null) {
                        return;
                    }
                    if (intent != null) {
                        String dataString = intent.getDataString();
                        if (dataString != null)
                            results = new Uri[]{Uri.parse(dataString)};
                    }
                }
                uploadMsgCopy.onReceiveValue(results);
                uploadMsgCopy = null;
            }
            break;
        default:
            super.onActivityResult(requestCode, resultCode, intent);
            break;
    }
}

0 个答案:

没有答案