Android Web视图文件上载不适用于小于5.0的版本

时间:2016-12-17 12:54:48

标签: android android-webview backwards-compatibility android-download-manager

我正在实施Web视图以在登录后加载用户的主页。 网络视图包含文件上传下载链接

我已经搜索了stackoverflow以获取有关如何实现这一点的信息,并且遇到了一些有用的链接,这些链接帮助我满足了某些级别的要求。我现在面临的问题是我的文件上传不适用于低于5.0的Android版本;对于5.0以上的版本,它似乎正常工作,只要我在网页视图中点击并上传按钮,就会弹出文件选择器(浏览器)。但是对于小于5.0的版本似乎根本没有任何动作。

我在Android工作的经验很少,这是我第一次在项目中使用Web视图。另外,这是我关于堆栈溢出的第一个问题,请原谅我的问题中的任何错误。 在此之前,请提供帮助,以便为我的解决方案提供帮助。总是会有一些解释。

  

粘贴我的示例代码:

     /**
     * 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();
}
  

这是我用于文件下载的代码(我只是粘贴它,以防任何人发现它有用)。任何   我们非常感谢以下代码中的修改

    /**
     * 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();
        }
    });
  

如果我需要提供任何其他信息,请发表评论并发布   它在这里。

1 个答案:

答案 0 :(得分:0)

这是我用于上传图片的代码,pdf你可以试试

        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();
                }

            }
        }
    }