Android HTML5圖片上傳實現方案
當前位置:點晴教程→知識管理交流
→『 技術文檔交流 』
![]() 一、HTML5 前端實現<!DOCTYPE html> <html> <head> <title>圖片上傳示例</title> </head> <body> <input type="file" id="uploadInput" accept="image/*" /> <img id="preview" style="max-width: 300px;" /> <button onclick="upload()">上傳</button> <script> const input = document.getElementById('uploadInput'); const preview = document.getElementById('preview'); // 圖片預覽 input.addEventListener('change', function(e) { const file = e.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = (e) => { preview.src = e.target.result; }; reader.readAsDataURL(file); } }); // 上傳函數 function upload() { const file = input.files[0]; if (!file) return; const formData = new FormData(); formData.append('image', file); fetch('https://your-server.com/upload', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { alert(data.message); }) .catch(error => { console.error('上傳失敗:', error); }); } </script> </body> </html> 二、Android WebView 配置1. 添加權限在 <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 2. 配置 WebViewWebView webView = findViewById(R.id.webView); WebSettings webSettings = webView.getSettings(); // 啟用 JavaScript 和 文件訪問 webSettings.setJavaScriptEnabled(true); webSettings.setAllowFileAccess(true); webSettings.setAllowContentAccess(true); // 處理文件上傳請求(針對 Android 5.0+) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } // 加載本地或遠程 HTML webView.loadUrl("file:///android_asset/upload.html"); 3. 處理權限請求(Android 6.0+)在 Activity 中動態請求存儲權限: private static final int REQUEST_STORAGE_PERMISSION = 1; private void checkPermissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_STORAGE_PERMISSION) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 權限已授予 } } } 在 Android WebView 中點擊 一、核心問題原因
二、解決方案步驟1. 添加文件選擇回調處理在 webView.setWebChromeClient(new WebChromeClient() { // 針對 Android 5.0+ (API 21+) @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { mFilePathCallback = filePathCallback; openFileChooser(); return true; } // 針對 Android < 5.0 (已棄用但需要兼容) @SuppressWarnings("deprecation") @Override public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { mUploadMessage = uploadMsg; openFileChooserLegacy(); } }); // 定義成員變量 private ValueCallback<Uri[]> mFilePathCallback; private ValueCallback<Uri> mUploadMessage; 2. 實現文件選擇器private void openFileChooser() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); startActivityForResult(intent, REQUEST_CODE_FILE_CHOOSER); } // 兼容舊版本 private void openFileChooserLegacy() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); startActivityForResult(Intent.createChooser(intent, "選擇圖片"), REQUEST_CODE_FILE_CHOOSER_LEGACY); } 3. 處理選擇結果在 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_FILE_CHOOSER) { if (resultCode == RESULT_OK && data != null) { Uri[] resultUris = WebChromeClient.FileChooserParams.parseResult(resultCode, data); if (mFilePathCallback != null) { mFilePathCallback.onReceiveValue(resultUris); mFilePathCallback = null; } } else { if (mFilePathCallback != null) { mFilePathCallback.onReceiveValue(null); mFilePathCallback = null; } } } else if (requestCode == REQUEST_CODE_FILE_CHOOSER_LEGACY) { if (resultCode == RESULT_OK && data != null) { Uri resultUri = data.getData(); if (mUploadMessage != null) { mUploadMessage.onReceiveValue(resultUri); mUploadMessage = null; } } else { if (mUploadMessage != null) { mUploadMessage.onReceiveValue(null); mUploadMessage = null; } } } } 4. 完整權限處理確保已動態請求 // 在 Activity 的 onCreate 中檢查權限 private static final int REQUEST_CODE_PERMISSION = 100; private void checkPermissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_PERMISSION) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 權限已授予,重新加載頁面或提示用戶操作 } } } 三、關鍵配置補充
2. AndroidManifest.xmlWebView webView = findViewById(R.id.webView); WebSettings settings = webView.getSettings(); // 必須配置 settings.setJavaScriptEnabled(true); settings.setAllowFileAccess(true); settings.setAllowContentAccess(true); // 針對 Android 5.0+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } 確保添加權限: <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ? 該文章在 2025/3/13 17:14:06 編輯過 |
關鍵字查詢
相關文章
正在查詢... |