关于文件拖放

本示例可参考示例文件"CaseStudy\WebViewer\拖放文件.Table"

出于安全考虑,拖放到WebViewer的文件默认只能获取文件名,无法获取路径,如果要自行处理拖入的文件,需要做特别的处理。

1、窗口的AfterLoad事件:

'''Async
Dim
wv As WebViewer = e.Form.Controls("WebViewer1").WebViewer
Await
wv.EnsureCoreWebView2Async(Nothing) '初始化浏览器
'
定义测试页面
Dim
html As String = <![CDATA[
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>
拖放测试</title>
    <style>
        #dropZone {
            width: 400px;
            height: 200px;
            border: 2px dashed #ccc;
            border-radius: 10px;
            margin: 50px auto;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f9f9f9;
        }
    </style>
</head>
<body>
    <div id="dropZone">
请拖放文件到此处</div>
    <script>
        //
window 级别阻止默认拖放行为
        window.addEventListener('dragover', function(e) {
            e.preventDefault();
        }, false);
        window.addEventListener('drop', function(e) {
            e.preventDefault();
        }, false);
        document.getElementById('dropZone').addEventListener('drop', function(e) {
            //
不需要再 preventDefaultwindow 已经处理了
            if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length > 0) {
                chrome.webview.postMessageWithAdditionalObjects(
                    { type: 'filesDropped', count: e.dataTransfer.files.length },
                    e.dataTransfer.files
                );
            }
        });
    </script>
</body>
</html>
]]>
.Valuewv.NavigateToString(html) '打开测试页面

2、WebViewer的WebMessageReceived事件代码:

Dim additionalObjs = e.AdditionalObjects
If
additionalObjs IsNot Nothing AndAlso additionalObjs.Count > 0 Then
   
' 遍历附加对象
   
For i As Integer = 0 To additionalObjs.Count - 1
       
Dim obj As Object = additionalObjs(i)    

        ' 判断对象类型(目前只有 CoreWebView2File
       
If TypeOf obj Is CoreWebView2File Then
           
Dim file As CoreWebView2File = DirectCast(obj, CoreWebView2File)
           
' 关键:通过 Path 属性获取文件的完整路径!
           
Dim filePath As String = file.Path
           
Dim fileName As String = System.IO.Path.GetFileName(filePath)
           
Dim fileSize As Long = New System.IO.FileInfo(filePath).Length           
            MessageBoxA.Show(
           
"文件 " & (i + 1) & ":" & vbCrLf &
           
"路径: " & filePath & vbCrLf &
           
"文件名: " & fileName & vbCrLf &
           
"大小: " & fileSize & " 字节"
            )
           
' 可以进一步处理文件,例如:
           
' - 读取文件内容
           
' - 上传到服务器
           
' - 复制到指定目录
           
' Dim content As String = FileSys.ReadAllText(filePath)
       
End If
   
Next
End
If


本页地址:http://www.foxtable.com/webhelp/topics/6393.htm