1.首先要设置文件选择处理器
using CefSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test.browser
{
class ChromiumSZDialogHandler : IDialogHandler
{
private string filePath = "";
public ChromiumSZDialogHandler(string selectFilePatH)
{
this.filePath = selectFilePatH;
}
//弹出选择文件框时,直接返回对应的文件路径!!
public bool OnFileDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, List<string> acceptFilters, IFileDialogCallback callback)
{
callback.Continue(new List<string> { this.filePath });
return true;
}
}
}
2.上传文件功能
// 上传文件功能
public static void uploadFile(ChromiumWebBrowser browser, string fileFullPath)
{
//设置文件选择处理器
browser.DialogHandler = new ChromiumSZDialogHandler(fileFullPath);
IFrame iframe2 = ChromiumUtils.getIFrame(browser, 0);
//先将元素滚动到能看到的位置
ExecuteJavaScriptAsync(iframe2, "document.getElementsByClassName('el-button el-button--primary el-button--medium')[3].scrollIntoView();");
//定位元素的坐标,然后点击鼠标
string x = excuteJSstr(iframe2, "document.getElementsByClassName('el-button el-button--primary el-button--medium')[3].getBoundingClientRect().x");
string y = excuteJSstr(iframe2, "document.getElementsByClassName('el-button el-button--primary el-button--medium')[3].getBoundingClientRect().y");
string width = excuteJSstr(iframe2, "document.getElementsByClassName('el-button el-button--primary el-button--medium')[3].getBoundingClientRect().width");
string height = excuteJSstr(iframe2, "document.getElementsByClassName('el-button el-button--primary el-button--medium')[3].getBoundingClientRect().height");
LogUtils.info("x = " + x + " | y = " + y + "| width = " + width + " | height = " + height);
double xx = double.Parse(x) + double.Parse(width) / 2;
double yy = double.Parse(y) + double.Parse(height) / 2;
// 点击
SendMouseClickEvent(iframe2.Browser.GetHost(), ((int)xx), ((int)yy), MouseButtonType.Left, false, 1, CefEventFlags.None);
// 松开
SendMouseClickEvent(iframe2.Browser.GetHost(), ((int)xx), ((int)yy), MouseButtonType.Left, true, 1, CefEventFlags.None);
}
public static void SendMouseClickEvent(this IBrowserHost host, int x, int y, MouseButtonType mouseButtonType, bool mouseUp, int clickCount, CefEventFlags modifiers)
{
ThrowExceptionIfBrowserHostNull(host);
host.SendMouseClickEvent(new MouseEvent(x, y, modifiers), mouseButtonType, mouseUp, clickCount);
}