欧美成人精品手机在线观看_69视频国产_动漫精品第一页_日韩中文字幕网 - 日本欧美一区二区

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

Android HTML5圖片上傳實現方案

Ccoffee
2025年3月13日 17:14 本文熱度 504
: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