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 编辑过 |
关键字查询
相关文章
正在查询... |