LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

Android HTML5图片上传实现方案

Ccoffee
2025年3月13日 17:14 本文热度 125
: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. 添加权限

在 AndroidManifest.xml 中添加权限:

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

2. 配置 WebView

WebView 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 中点击 <input type="file"> 无法打开图片列表的问题,通常是由于 WebView 未正确配置文件选择支持或 权限问题 导致。以下是完整的解决方案:


一、核心问题原因

  1. WebView 未配置文件选择回调处理

  2. 未正确处理 Android 权限

  3. WebView 安全策略限制


二、解决方案步骤

1. 添加文件选择回调处理

在 Activity 或 Fragment 中实现 WebChromeClient 并重写文件选择方法:

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. 处理选择结果

在 onActivityResult 中处理返回的图片 URI:

@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. 完整权限处理

确保已动态请求 READ_EXTERNAL_STORAGE 权限:

// 在 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) {

            // 权限已授予,重新加载页面或提示用户操作

        }

    }

}


三、关键配置补充

  1. WebView 初始化

2. AndroidManifest.xml

WebView 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 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved