Android Web view file upload not working for versions less than 5.0

894 views Asked by At

I am implementing a Web view to load a home page of a user after logging in. The web view consists of both file upload and download links.

I have searched stackoverflow for info on how to implement this, and came across some useful links, which helped me to meet my requirements up to some level. The problem I'm facing right now is that my file upload is not working for Android versions less than 5.0; for versions above 5.0, it seems to be working and the file chooser(browser) seems to pop up as soon as I click and upload button inside the web view. But there seems to be no action at all for versions less than 5.0.

I have only little experience working in Android, and this is the first time I'm using web view in a project. Also, this is my first question on stack overflow, so kindly excuse any mistakes in my question. Thanks in advance to whoever provides some help in arriving at my solution. Some explanation would always be appreciated.

Pasting my sample code below:

     /**
     * Settings for WebView & Loading webView from URL
     */
    WebSettings webSettings = webView.getSettings();
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setJavaScriptEnabled(true);

    webSettings.setAllowFileAccess(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setAllowContentAccess(true);

    dialog = ProgressDialog.show(this, "Loading", "Please wait...", true);
    dialog.setCancelable(true);
    /**
     * Checking device release version
     */
    Log.d("ReleaseVersion", "=" + androidOS);
    if (androidOS == 16) {
        fourBoolean = true;
    }
    if (!fourBoolean) {
        if (androidOS > 10 && androidOS < 21) {
            firstBoolean = true;
        } else if (androidOS >= 21) {
            fiveBoolean = true;
        }
    }


    /**
     * fourBoolean gives TRUE if Target SDK version is 4.1
     * firstBoolean gives TRUE if Target SDK version is 3.0+ (till 5.0, except 4.1)
     * fiveBoolean gives TRUE if Target SDK version is 5.0+
     */
    Log.d("ReleaseVersionFlags", "=" + "fourBoolean" + "=" + fourBoolean);
    Log.d("ReleaseVersionFlags", "=" + "firstBoolean" + "=" + firstBoolean);
    Log.d("ReleaseVersionFlags", "=" + "fiveBoolean" + "=" + fiveBoolean);

    /**
     * Method for uploading files to WebView (based on Target SDK version)
     */

    if (fourBoolean) {
        Log.d("ReleaseVersionStatus", "=" + "4.1");
        webView.setWebChromeClient(new WebChromeClient() {
            //For Android 4.1 only
            protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.d("ReleaseVersionInside", "=" + "inside 4.1 ONE");
                mUploadMessage = uploadMsg;
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            protected void openFileChooser(ValueCallback<Uri> uploadMsg) {
                Log.d("ReleaseVersionInside", "=" + "inside 4.1 TWO");
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }
        });
    }
    if (firstBoolean) {
        Log.d("ReleaseVersionStatus", "=" + "3.0+");
        webView.setWebChromeClient(new WebChromeClient() {
            // For 3.0+ Devices (Start)
            // onActivityResult attached before constructor
            protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                Log.d("ReleaseVersionInside", "=" + "inside 3.0");
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }
        });
    }
    if (fiveBoolean) {
        Log.d("ReleaseVersionStatus", "=" + "5.0+");
        webView.setWebChromeClient(new WebChromeClient() {
            // For Lollipop 5.0+ Devices
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                Log.d("ReleaseVersionInside", "=" + "inside 5.0");
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = filePathCallback;

                Intent intent = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    intent = fileChooserParams.createIntent();
                }
                try {
                    startActivityForResult(intent, REQUEST_SELECT_FILE);
                } catch (ActivityNotFoundException e) {
                    uploadMessage = null;
                    Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
                    return false;
                }
                return true;
            }
        });
    }


/**
 * Override method to get result from FileChooser activity (File Upload)
 *
 * @param requestCode
 * @param resultCode
 * @param intent
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if (requestCode == REQUEST_SELECT_FILE) {
            if (uploadMessage == null)
                return;
            uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
            uploadMessage = null;
        }
    } else if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage)
            return;
        // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
        // Use RESULT_OK only if you're implementing WebView inside an Activity
        Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    } else
        Toast.makeText(getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
}

This is the code which I am using for file download (I'm just pasting it, in case anyone might find it useful). Any modifications in the below code is appreciated.

    /**
     * Method for downloading files from WebView
     */
    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            Log.d("DownloadURL", "=" + url);
            if (url.endsWith(".pdf")) {
                Log.d("DownloadURLMime", "=" + "application/" + FilenameUtils.getExtension(url));
                request.setMimeType("application/" + FilenameUtils.getExtension(url));
            } else {
                Log.d("DownloadURLMime", "=" + mimeType);
                request.setMimeType(mimeType);
            }
            String cookies = CookieManager.getInstance().getCookie(url);
            request.addRequestHeader("cookie", cookies);
            request.addRequestHeader("User-Agent", userAgent);
            request.setDescription("APP_NAME");
            request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Toast.makeText(getApplicationContext(), "Downloading...", Toast.LENGTH_SHORT).show();
        }
    });

If I need to provide any additional info, just comment and I'll post it here.

1

There are 1 answers

0
Anuj Gupta On

This is a code which i am using for upload image and pdf you can try it

        private void selectImage() {
        final CharSequence[] options = { "Take Photo", "Choose Photo from Gallery","Choose PDF",
                "Cancel" };
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("Add Attachment !");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Take Photo"))
                {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                    Uri photoURI;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
                        photoURI = FileProvider.getUriForFile(activity, activity.getApplicationContext().getPackageName() + ".provider", f);
                    } else{
                        photoURI =Uri.fromFile(f);
                    }
//                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
                    startActivityForResult(intent, 1);
                }
                else if (options[item].equals("Choose Photo from Gallery"))
                {
                    Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);
                }
                else if (options[item].equals("Choose PDF"))
                {
                    Intent intent = new   Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("application/pdf");
                    startActivityForResult(intent.createChooser(intent, "Select Pdf"), 3);
                }
                else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {

                File f = new File(Environment.getExternalStorageDirectory().toString());

                for (File temp : f.listFiles()) {
                    Log.d("File Name",Environment.getExternalStorageDirectory()+"/Rc_Doc/"+temp.getName());
                    if (temp.getName().equals("temp.jpg")) {

                        f = temp;
                        fileSize=f.length()+"";
                        break;

                    }

                }

                try {

                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();



                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),

                            bitmapOptions);
                    type ="image/jpeg";
                    imageBase64=getStringImage(bitmap);
                    imageName="Rc_Doc_"+CommanVar.agentCode+String.valueOf(System.currentTimeMillis()) + ".jpg";
//                    display.setImageBitmap(bitmap);
                    sendImageRequest("saveImage.php",1);

                } catch (Exception e) {

                    e.printStackTrace();

                }

            } else if (requestCode == 2) {

                Uri selectedImage = data.getData();
                String uriToString = selectedImage.getPath();
                File file = new File(uriToString);
                fileSize=file.length()+"";
                String[] filePath = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                Log.d("Path", picturePath + "");
                if(picturePath.endsWith("jpg") || picturePath.endsWith("png") || picturePath.endsWith("jpeg") ) {
                    String[] filename = picturePath.split("/");
//                    fileName.setText(filename[filename.length - 1]);
                    imageName = filename[filename.length - 1];
                    imageBase64 = getStringImage(thumbnail);
                    type = "image/jpeg";
                    sendImageRequest("saveImage.php", 2);
                }
                else{
                    ErrorDialogFragment alert = new ErrorDialogFragment();
                    alert.showDialog(VoucherEntryActivity.this, "You Can Upload only JPG,JPEG or PNG files....");
                }
//                display.setImageBitmap(thumbnail);

            }
            else if (requestCode == 3) {

                Uri selectedPDF = data.getData();
                String uriToString = selectedPDF.getPath();

                Log.d("path2",uriToString);
                File file = new File(uriToString);
                int size = (int) file.length();
                fileSize=size+"";
                byte[] bytes = new byte[size];
                String docPath = file.getAbsolutePath();
                Log.d("path",docPath);
                String [] filename =docPath.split("/");
                Toast.makeText(this, docPath+"", Toast.LENGTH_SHORT).show();
                if(docPath.endsWith("pdf"))
                {
                    if(size <  1048576)
                    {
                        try {
                            BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
                            buf.read(bytes, 0, bytes.length);
                            buf.close();
                            imageBase64 = Base64.encodeToString(bytes, Base64.DEFAULT);
                            imageName=filename[filename.length-1];
//                            fileName.setText(filename[filename.length-1]);
                            type ="application/pdf";
                            sendImageRequest("saveImage.php",3);
//                            Toast.makeText(activity, "Ok", Toast.LENGTH_SHORT).show();
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }
                    else{

                        ErrorDialogFragment alert = new ErrorDialogFragment();
                        alert.showDialog(VoucherEntryActivity.this, "File Is too big...Maximum File Size 1 MB..");
//                        Toast.makeText(activity, "File Is too big...Maximum File Size 1 MB", Toast.LENGTH_SHORT).show();
                    }

                }
                else{
                    ErrorDialogFragment alert = new ErrorDialogFragment();
                    alert.showDialog(VoucherEntryActivity.this, "Please Select Only PDF File..");
//                    Toast.makeText(activity, "Please Select Only PDF File", Toast.LENGTH_SHORT).show();
                }

            }
        }
    }