如何在 C# 中使用 Geckofx 选择本地文件并将其上传到网站? [英] How to choose and upload a local file to a website using Geckofx in C#?

查看:34
本文介绍了如何在 C# 中使用 Geckofx 选择本地文件并将其上传到网站?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 winform 应用程序中使用 Geckofx 来填写网站上的表单.其中一个控件是选择文件"按钮,可让您选择并上传本地文件.我想通过代码完全执行此过程来自动执行此过程.

I'm using Geckofx in my winform application to fill a form on a website. One of the controls is a button "Choose Files" which lets you select and upload a local file. I want to automate this process by doing this fully via code.

我设法通过代码点击了这个按钮:

I managed to click this button via code:

Gecko.DOM.GeckoButtonElement button = new Gecko.DOM.GeckoButtonElement(doc.GetElementsByClassName("choose_files_btn").First().DomObject);
button.Click();

因此会自动打开一个文件对话框,但我想自动化文件选择部分并单击确定".我尝试检查网页以查看是否可以将本地文件的路径分配给某个 Gecko 元素,但找不到此类内容.

As a result a file dialog is opened automatically but I want to automate the file choosing part and clicking 'OK' as well. I tried inspecting the webpage to find whether I could assign the path of my local file to some Gecko element but couldn't find anything of this sort.

我也想过处理打开文件对话框的事件,但是在 Gecko 中找不到任何事件处理程序.我找到了 Gecko.LauncherDialog.Download 事件处理程序,它用于处理使用 Geckofx 浏览器下载文件.但是没有这样的事件处理程序用于使用 Geckofx 浏览器上传文件,如果有并且我错过了,请告诉.

I also thought about handling the event of opening the file dialog but couldn't find any event handler in Gecko. I found Gecko.LauncherDialog.Download event handler which is used for handling downloading a file using Geckofx browser. But there's no such event handler for uploading files using Geckofx browser, if there is and I missed it, do tell.

也许我可以使用不是来自 Gecko 而是来自 System 的事件处理程序,如果我编写一个事件处理程序来捕获每个打开的文件对话框事件,但我不知道这是否可能.

Maybe I can use an event handler not from Gecko but from System, if I write an event handler which will catch every open file dialog event but I don't know whether that's even possible.

推荐答案

这里有一个解决方案,上传时不显示文件上传对话框:

Here is a solution, to upload without showing the file upload dialog:

GeckoHtmlElement el = webbrowser.DomDocument.GetElementsByTagName("input").FirstOrDefault(elz => elz.GetAttribute("type") == "file"); //inpout type file element
var fileNames = new IntPtr[1];
fileNames[0] = new Gecko.CustomMarshalers.WStringMarshaler().MarshalManagedToNative(file); //file = path to file you want to upload


var domInput = Xpcom.QueryInterface<nsIDOMHTMLInputElement>(el.DOMHtmlElement);
domInput.MozSetFileNameArray(fileNames, (uint)fileNames.Length);

Marshal.ReleaseComObject(domInput);

DomEventArgs ev = webbrowser.Document.CreateEvent("HTMLEvents");
var webEvent = new Event(webbrowser.Window.DomWindow, ev.DomEvent as nsISupports);
webEvent.InitEvent("change", true, true);
el.GetEventTarget().DispatchEvent(ev);

new Gecko.CustomMarshalers.WStringMarshaler().CleanUpNativeData(fileNames[0]); //delete everything

这篇关于如何在 C# 中使用 Geckofx 选择本地文件并将其上传到网站?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆