0
点赞
收藏
分享

微信扫一扫

Android(五十八):WebView - 解决 <input type=“file“ />标签点击无效问题


展示

Android(五十八):WebView - 解决 <input type=“file“ />标签点击无效问题_android

源码

Web H5端

<input id="file" type="file" onchange="handleUploadFile(this)"></input>
<script>// 文件上传
const handleUploadFile = ({files}) => {
let formData = new FormData();
Object.values(files).forEach(file => {
formData.append('file', file);
});
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://10.10.1.184:8888/upload', true);
xhr.send(formData);
xhr.onload = function () {
if (this.status === 200) {
alert('上传成功')
}
}
}</script>

服务端

参考:​​Node.js(五):GET、POST 请求 文件上传​​

Android端

  • ​MainActivity.cs​

_webView.SetWebChromeClient(new MyWebChromeClient(OpenFileChooserActivity));

// 打开文件管理器
private void OpenFileChooserActivity()
{
var intent = new Intent(Intent.ActionGetContent);
intent.PutExtra(Intent.ExtraAllowMultiple, true);
intent.SetType("*/*");
StartActivityForResult(intent, 1);
}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
// 文件上传
if (requestCode == 1)
{
// 选择了文件并确认
if (resultCode == Result.Ok)
{
Uri[] uris;
if (data.Data != null)
uris = new[] { data.Data };
else
{
uris = new Uri[data.ClipData!.ItemCount];
for (var i = 0; i < data.ClipData?.ItemCount; i++)
{
uris[i] = data.ClipData.GetItemAt(i)?.Uri;
}
}

MyWebChromeClient.FilePathCallback.OnReceiveValue(uris);
}
// 未选择文件并返回
else
MyWebChromeClient.FilePathCallback.OnReceiveValue(null);
}
}

  • ​Scripts/MyWebChromeClient.cs​

using System;
using Android.Webkit;

namespace PrimaryBlankApp.Scripts
{
public class MyWebChromeClient : WebChromeClient
{
private readonly Action _action;
public static IValueCallback FilePathCallback;

public MyWebChromeClient(Action action)
{
_action = action;
}

// 解决 WebView 中 <input type="file" /> 上传标签点击无效方法
public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
{
FilePathCallback = filePathCallback;
_action();
return true;
}
}
}


举报

相关推荐

0 条评论