1. 程式人生 > >在Android瀏覽器中通過WebView呼叫相機拍照/選擇檔案 上傳到伺服器

在Android瀏覽器中通過WebView呼叫相機拍照/選擇檔案 上傳到伺服器

               

最近做的一個專案中,有這樣一個要求,在瀏覽器中呼叫系統的拍照功能或者選擇檔案,然後將檔案上傳到伺服器,類似修改頭像。        簡單而言,就是在一個html頁面中有這樣一段程式碼 <input class="filePrew" type="file" capture="camera" accept="image/*" name="image">

剛開始的時候,沒有感覺很難的,因為在UC瀏覽器、系統自帶的瀏覽器中都可以進行拍照/檔案管理器選擇,可是在自己所寫的Activity中卻不行。後來實在是沒有思路了,就在網上找了一下,發現要        實現這種功能,都是在webview的WebChromeClient中覆蓋掉openFileChooser方法,注意openFileChooser方法在WebChromeClient中有@hide標記。這裡只管重寫即可,下面將主要程式碼貼出來,做個記錄        

  1. private ValueCallback<Uri> mUploadFile;  
  2.     /**拍照/選擇檔案請求碼*/
  3.     privatestaticfinalint REQUEST_UPLOAD_FILE_CODE = 12343;  
  4.     privatevoid setWebChromeClient()  
  5.     {  
  6.         if (null != mMainWebView)  
  7.         {  
  8.             mMainWebView.setWebChromeClient(new WebChromeClient()  
  9.             {  
  10.                 // Andorid 4.1+
  11.                 publicvoid openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture)  
  12.                 {  
  13.                     openFileChooser(uploadFile);  
  14.                 }  
  15.                 // Andorid 3.0 +
  16.                 publicvoid openFileChooser(ValueCallback<Uri> uploadFile, String acceptType)  
  17.                 {  
  18.                     openFileChooser(uploadFile);  
  19.                 }  
  20.                 // Android 3.0
  21.                 publicvoid openFileChooser(ValueCallback<Uri> uploadFile)  
  22.                 {  
  23.                     // Toast.makeText(WebviewActivity.this, "上傳檔案/圖片",Toast.LENGTH_SHORT).show();
  24.                     mUploadFile = uploadFile;  
  25.                     startActivityForResult(Intent.createChooser(createCameraIntent(), "Image Browser"), REQUEST_UPLOAD_FILE_CODE);  
  26.                 }  
  27.             });  
  28.         }  
  29.     }  
  30.     private Intent createCameraIntent()  
  31.     {  
  32.         Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//拍照
  33.         //=======================================================
  34.         Intent imageIntent = new Intent(Intent.ACTION_GET_CONTENT);//選擇圖片檔案
  35.         imageIntent.setType("image/*");  
  36.         //=======================================================
  37.         return cameraIntent;  
  38.     }  
  39.     //最後在OnActivityResult中接受返回的結果
  40.     protectedvoid onActivityResult(int requestCode, int resultCode, Intent data)  
  41.     {  
  42.         if (requestCode == REQUEST_UPLOAD_FILE_CODE && resultCode == RESULT_OK)  
  43.         {  
  44.             if (null == mUploadFile)  
  45.             {  
  46.                 return;  
  47.             }  
  48.             Uri result = (null == data) ? null : data.getData();  
  49.             if (null != result)  
  50.             {  
  51.                 ContentResolver resolver = this.getContentResolver();  
  52.                 String[] columns = { MediaStore.Images.Media.DATA };  
  53.                 Cursor cursor = resolver.query(result, columns, nullnullnull);  
  54.                 cursor.moveToFirst();  
  55.                 int columnIndex = cursor.getColumnIndex(columns[0]);  
  56.                 String imgPath = cursor.getString(columnIndex);  
  57.                 System.out.println("imgPath = " + imgPath);  
  58.                 if (null == imgPath)  
  59.                 {  
  60.                     return;  
  61.                 }  
  62.                 File file = new File(imgPath);  
  63.                    //將圖片處理成大小符合要求的檔案
  64.                 result = Uri.fromFile(handleFile(file));  
  65.                 mUploadFile.onReceiveValue(result);  
  66.                 mUploadFile = null;       
  67.             }  
  68.         }  
  69.         super.onActivityResult(requestCode, resultCode, data);  
  70.     }  
  71.     /**處理拍照/選擇的檔案*/  
  72.     private File handleFile(File file)  
  73.     {  
  74.         DisplayMetrics dMetrics = getResources().getDisplayMetrics();  
  75.         BitmapFactory.Options options = new Options();  
  76.         options.inJustDecodeBounds = true;  
  77.          BitmapFactory.decodeFile(file.getAbsolutePath(), options);  
  78.         int imageWidth = options.outWidth;  
  79.         int imageHeight = options.outHeight;  
  80.         System.out.println("  imageWidth = " + imageWidth + " imageHeight = " + imageHeight);  
  81.         int widthSample = (int) (imageWidth / (dMetrics.density * 90));  
  82.         int heightSample = (int) (imageHeight / (dMetrics.density * 90));  
  83.         System.out.println("widthSample = " + widthSample + " heightSample = " + heightSample);  
  84.         options.inSampleSize = widthSample < heightSample ? heightSample : widthSample;  
  85.         options.inJustDecodeBounds = false;  
  86.         Bitmap newBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);  
  87.         System.out.println("newBitmap.size = " + newBitmap.getRowBytes() * newBitmap.getHeight());  
  88.         File handleFile = new File(file.getParentFile(), "upload.png");  
  89.         try
  90.         {  
  91.             if (newBitmap.compress(CompressFormat.PNG, 50new FileOutputStream(handleFile)))  
  92.             {  
  93.                 System.out.println("儲存圖片成功");  
  94.             }  
  95.         }  
  96.         catch (FileNotFoundException e)  
  97.         {  
  98.             e.printStackTrace();  
  99.         }  
  100.         return handleFile;  
  101.     }  
這樣就可以在WebView中上傳檔案了。記得要新增相應的許可權!         參考:http://developer.android.com/about/versions/android-3.0.html

  http://blog.sina.com.cn/s/blog_5749ead90101clrn.html