Breaking News

How to enable Upload button to Upload files in Android WebView

How to enable Upload button to Upload files in Android WebView


In this post, we will enable the upload button in Android WebView to upload files to a Website.

Some Websites, like a video/mp3 converter, educational website. You have to upload something to proceed to the next step and in our Android WebView, we have to enable that upload button programmatically so that you can upload your needed documents to a website.


For that do some code in your Browser activity. 


BrowserActivity.java  before onCreate
   private final static int FCR = 1;  
   private String mCM;  
   private ValueCallback<Uri> mUM;  
   private ValueCallback<Uri[]> mUMA;  
   @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;  
       }  
     }  
   }  

In OnCreate in BrowserActivity.java
When you finished initializing your WebView.


 if (Build.VERSION.SDK_INT >= 21) {  
       webSettings.setMixedContentMode(0);  
       wv.setLayerType(View.LAYER_TYPE_HARDWARE, null);  
     } else if (Build.VERSION.SDK_INT >= 19) {  
       wv.setLayerType(View.LAYER_TYPE_HARDWARE, null);  
     } else if (Build.VERSION.SDK_INT < 19) {  
       wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);  
     }  
     wv.setWebViewClient(new Callback());  
     wv.setWebChromeClient(new WebChromeClient() {  
       //For Android 3.0+  
       public void openFileChooser(ValueCallback<Uri> uploadMsg) {  
         mUM = uploadMsg;  
         Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
         i.addCategory(Intent.CATEGORY_OPENABLE);  
         i.setType("*/*");  
         Refresh.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);  
       }  
       // For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this  
       public void openFileChooser(ValueCallback uploadMsg, String acceptType) {  
         mUM = uploadMsg;  
         Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
         i.addCategory(Intent.CATEGORY_OPENABLE);  
         i.setType("*/*");  
         Refresh.this.startActivityForResult(  
             Intent.createChooser(i, "File Browser"),  
             FCR);  
       }  
       //For Android 4.1+  
       public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {  
         mUM = uploadMsg;  
         Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
         i.addCategory(Intent.CATEGORY_OPENABLE);  
         i.setType("*/*");  
         Refresh.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), Refresh.FCR);  
       }  
       //For Android 5.0+  
       public boolean onShowFileChooser(  
           WebView webView, ValueCallback<Uri[]> filePathCallback,  
           WebChromeClient.FileChooserParams fileChooserParams) {  
         if (mUMA != null) {  
           mUMA.onReceiveValue(null);  
         }  
         mUMA = filePathCallback;  
         Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
         if (takePictureIntent.resolveActivity(Refresh.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, "Choose an Action");  
         chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);  
         startActivityForResult(chooserIntent, FCR);  
         return true;  
       }  
     });  


And Three methods after OnCreate finished in BrowserActivity.java
 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);  
   }  
 @Override   
   public void onConfigurationChanged(Configuration newConfig) {   
    super.onConfigurationChanged(newConfig);   
   }   
   public class Callback extends WebViewClient {   
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {   
     Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();   
    }   
   }   



Now, You can successfully upload files to a WebSite with Android WebView.


Follow us for more posts like this, 
Subscribe Harpreet studio on Youtube  
Like Harpreet Studio on Facebook  
Follow me on Instagram 

18 comments:

  1. How to make Website like you make a playlist on it with voice on YouTube Give Value to others

    ReplyDelete
  2. In the time of advanced mobile phones and tablets, Android controlled gadgets have effectively figured out how to cut an extraordinary personality for them. Brighter Guide

    ReplyDelete
  3. hello guys the code looks great but it seems you forgot to define the refresh method. If you can upload the revised code sample that would be perfect!

    ReplyDelete
    Replies
    1. Too late reply, but in video errors are resolved, and you can also delete that refresh.this or replace with your activity name

      Delete
  4. Controversial Fat Loss Method Deemed "Too Extreme" For The General Public

    Did you know taking a baby aspirin 3x a day can actually increase your metabolism?
    Or that chewing just one piece of nicotine gum forces your body to incinerate stored body fat?
    The author lost 13 pounds of fat in a month. So why did his method get banned?
    Those are just a couple of the tips revealed inside a controversial fat loss manual.
    Some brave souls used this plan to quickly drop 10, 20, even 30 pounds of fat in just a few short weeks. In fact, the author of this book wrote his manual after dropping 13 pounds and getting down to single-digit body fat in less than a month. If you can get your hands on a copy of this book, you'll immediately see why it's so effective. Unfortunately tracking down this book is no easy task. More information in the next link

    Controversial Fat Loss Method

    ReplyDelete
  5. There is an expanding necessity of sending enormous files to a far off area. transfer files

    ReplyDelete
  6. Any news about Refresh method?

    ReplyDelete
    Replies
    1. Min 3:12 i realized that Refresh method is the MainActivity class

      Delete
    2. Too late reply, but yes you are right, in video errors are resolved, and you can also delete that refresh.this or replace with your activity name

      Delete
  7. Hi, am new to Kotlin Android Studio. Where do I find Browserctivity.java. How do I use this on a new project.

    ReplyDelete
    Replies
    1. Browser activity is just your activity name, replace it with your activity name..

      Delete
  8. Please give me a full source code.

    ReplyDelete
  9. You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming. file upload

    ReplyDelete
  10. hie guys any new on refresh

    ReplyDelete
    Replies
    1. In video errors are resolved, and you can also delete that refresh.this or replace with your activity name

      Delete