Make Android WebView Support File Upload

How to make android webview support image or files upload

The webview of android can be configured to support file upload, the code below can make the webview support file upload

The code is a bit long, so you need carefully implement it to your webview activity, remeber to place the code below the setWebviewClient.

For reference, i will upload the full code file here in the end of this post, you can use it for reference.

 

The code for enabling file upload in webview

 

First, add these code above the oncreate method

 

    private static final int REQUEST_STORAGE = 1;
    private static final int REQUEST_LOCATION = 2;
    public ValueCallback<Uri> mUploadMessage;
    public static final int FILECHOOSER_RESULTCODE = 5173;

 

Then add this code below webviewclient

 

public void openFileChooser(ValueCallback<Uri> uploadMsg) {
              this.openFileChooser(uploadMsg, "*/*");
          }

          public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
              this.openFileChooser(uploadMsg, acceptType, null);
          }

          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("*/*");
              WebActivityDark.this.startActivityForResult(Intent.createChooser(i, "File Browser"),
                      FILECHOOSER_RESULTCODE);
          }


          public boolean onShowFileChooser(


                  WebView webView, ValueCallback<Uri[]> filePathCallback,
                  FileChooserParams fileChooserParams) {
              if (mUMA != null) {
                  mUMA.onReceiveValue(null);
              }
              mUMA = filePathCallback;
              Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
              if (takePictureIntent.resolveActivity(WebActivityDark.this.getPackageManager()) != null) {
                  File photoFile = null;
                  try {
                      photoFile = createImageFile();
                      takePictureIntent.putExtra("PhotoPath", mCM);
                  } catch (IOException ex) {
                      Log.e(TAG, "Image file creation failed", ex);
                  }
                  if (photoFile != null) {
                      mCM = "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("*/*");
              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, FCR);
              return true;
          }
      });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
      super.onActivityResult(requestCode, resultCode, intent);
      if (Build.VERSION.SDK_INT >= 21) {
          Uri[] results = null;
          //Check if response is positive
          if (resultCode == Activity.RESULT_OK) {
              if (requestCode == FCR) {
                  if (null == mUMA) {
                      return;
                  }
                  if (intent == null) {
                      //Capture Photo if no image available
                      if (mCM != null) {
                          results = new Uri[]{Uri.parse(mCM)};
                      }
                  } else {
                      String dataString = intent.getDataString();
                      if (dataString != null) {
                          results = new Uri[]{Uri.parse(dataString)};
                      }
                  }
              }
          }
          mUMA.onReceiveValue(results);
          mUMA = null;
      } else {
          if (requestCode == FCR) {
              if (null == mUM) return;
              Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
              mUM.onReceiveValue(result);
              mUM = null;
          }
      }
  }


  private class Callback extends WebViewClient {
      @Override
      public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
          Toast.makeText(getApplicationContext(), "Failed loading! try reloading", Toast.LENGTH_SHORT).show();
          webl.loadUrl("file:///android_asset/help.html");
      }
  }

  // Create an image file
  private File createImageFile() throws IOException {
      @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
      String imageFileName = "img_" + timeStamp + "_";
      File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
      return File.createTempFile(imageFileName, ".jpg", storageDir);


  }

 

For your reference, the full java code is here WebActivity

, ,

Post navigation

Leave a Reply

Your email address will not be published. Required fields are marked *