【问题标题】:File Upload in WebView Android StudioWebView Android Studio 中的文件上传
【发布时间】:2018-01-18 02:39:46
【问题描述】:

我想允许来自我的 WebView Android 应用程序的上传按钮。由于我不是 Android 开发人员,因此我需要您的帮助才能为 Android WebView 启用图像上传器。这是我的 MainActivity 文件。

package com.hfzgk.hfzgk;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    WebView myWeb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setPage();
    }

    private void setPage(){

        myWeb = (WebView) findViewById(R.id.myViewId);
        WebSettings myseeting = myWeb.getSettings();
        myseeting.setJavaScriptEnabled(true);
        myWeb.loadUrl("http://www.hfzgk.tk/");
        myWeb.setWebViewClient(new WebViewClient());
    }

    @Override
    public void onBackPressed() {
        if (myWeb.canGoBack())
            myWeb.goBack();
        else
        super.onBackPressed();
    }
}

【问题讨论】:

    标签: android android-studio webview


    【解决方案1】:

    试试这个作为你的 mainactivity.java:

    import android.content.Context;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import android.webkit.JavascriptInterface;
    import android.webkit.ValueCallback;
    import android.webkit.WebChromeClient;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import java.io.*;
    import android.util.*;
    import java.text.*;
    import android.annotation.*;
    import java.util.*;
    import android.app.*;
    import android.provider.*;
    import android.os.*;
    import android.webkit.*;
    
    public class MainActivity extends Activity {
    
    public static final int REQUEST_CODE_LOLIPOP = 1;
    private final static int RESULT_CODE_ICE_CREAM = 2;
    private WebView webView;
    private ValueCallback<Uri[]> mFilePathCallback;
    private String mCameraPhotoPath;
    private ValueCallback<Uri> mUploadMessage;
    
    private String url ="http://up.example.com";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    
    webView = (WebView) findViewById(R.id.wbvw);
    setUpWebViewDefaults(webView);
    webView.loadUrl(url);
    
    
    
       webView.setWebChromeClient(new WebChromeClient() {
            private String TAG;
            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"),
                                       RESULT_CODE_ICE_CREAM);
    
            }
            // For Android 3.0+
             public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"),
                                       RESULT_CODE_ICE_CREAM);
            }
            //For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"),
                                       RESULT_CODE_ICE_CREAM);
    
            }
            //For Android5.0+
            public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                }
                mFilePathCallback = filePathCallback;
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                    // Create the File where the photo should go
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                    } catch (IOException ex) {
                        // Error occurred while creating the File
                        Log.e(TAG, "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));
                    } 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};
                } 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, REQUEST_CODE_LOLIPOP);
    
                return true;
            }
           });
          }
        private File createImageFile() throws IOException {
       // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES);
        File imageFile = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
         );
       return imageFile;
        }
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        private void setUpWebViewDefaults(WebView webView) {
        WebSettings settings = webView.getSettings();
       // Enable Javascript
        settings.setJavaScriptEnabled(true);
        // Use WideViewport and Zoom out if there is no viewport defined
       settings.setUseWideViewPort(true);
       settings.setLoadWithOverviewMode(true);
       // Enable pinch to zoom without the zoom buttons
       settings.setBuiltInZoomControls(true);
       if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // Hide the zoom controls for HONEYCOMB+
        settings.setDisplayZoomControls(false);
       }
       // Enable remote debugging via chrome://inspect
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
       }
       // We set the WebViewClient to ensure links are consumed by the WebView rather
       // than passed to a browser if it can
       webView.setWebViewClient(new WebViewClient());
        }
       @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case RESULT_CODE_ICE_CREAM:
            Uri uri = null;
            if (data != null) {
                uri = data.getData();
            }
            mUploadMessage.onReceiveValue(uri);
            mUploadMessage = null;
            break;
          case REQUEST_CODE_LOLIPOP:
            Uri[] results = null;
            // Check that the response is a good one
            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;
            break;
          }
          }
    
          }
    

    在你的activitymain.xml中也添加这个:

     <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    
    
    
    <WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    
    </WebView>
    
    
    </RelativeLayout>
    

    最后不要忘记在您的 manifest.xml 中授予权限:

     <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.aashiq.multipleimg">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    
      <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        </application>
    
      </manifest>
    

    【讨论】:

      猜你喜欢
      • 2015-04-03
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      • 1970-01-01
      • 2016-08-02
      相关资源
      最近更新 更多