0

我實現Web視圖登錄後加載用戶的主頁。 Web視圖既包括文件的上傳的下載鏈接Android的Web視圖文件上傳不工作的版本低於5.0

我已經搜索了關於如何實現這個信息的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(); 
     } 
    }); 

如果我需要提供任何額外的信息,只是評論,我會在這裏發表 它。

回答

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

      } 
     } 
    } 
相關問題