上传文件不起作用 - 需要帮助

PiE*_*PiE 4 .net c# file-upload webbrowser-control winforms

我正在尝试使用WebBrowser控件上传文件(图像).似乎无法做到并需要一些帮助.

这是Html:

<form action="https://post.testsite.com/k/IOkurrwY4xGI_EJMbjF5pg/zMNsR" method="post" enctype="multipart/form-data">
    <input type="hidden" name="cryptedStepCheck" value="U2FsdGVkX18yNzEwMjcxMJdrv2IidjtpGSCPzHNblWk02eJAJ6DFXFXic-Am1lTPMYL7k7XDoH0">
    <input type="hidden" name="a" value="add">
    <input class="file" type="file" name="file" multiple="multiple">
    <button class="add" type="submit" name="go"  value="add image">add image</button>
</form>
Run Code Online (Sandbox Code Playgroud)

这是C#代码......

        elements = webBrowser.Document.GetElementsByTagName("input");
        foreach (HtmlElement file in elements)
        {
            if (file.GetAttribute("name") == "file")
            {
                file.Focus();
                file.InvokeMember("Click");
                SendKeys.Send("C:\\Images\\CCPhotoID.jpg" + "{ENTER}");
            }
        }
Run Code Online (Sandbox Code Playgroud)

请注意,文件上载按钮出现,但无法在文件名区域中输入任何文件名.

nos*_*tio 6

IMO,你要做的确实是UI测试自动化的合法场景.IIRC,在IE的早期版本中,可以<input type="file"/>使用文件名填充字段,而不显示Choose File对话框.出于安全原因,这不再可能,因此您必须将密钥发送到对话框.

这里的问题是file.InvokeMember("Click")显示模态对话框,并且您希望将键发送到对话框,但在对话框关闭SendKeys.Send执行(它是模态的,后跟所有).您需要先打开对话框,然后发送密钥并将其关闭.

这个问题可以使用WinForms来解决Timer,但我更喜欢使用async/awaitTask.Delay为此(工作代码):

async Task PopulateInputFile(HtmlElement file)
{
    file.Focus();

    // delay the execution of SendKey to let the Choose File dialog show up
    var sendKeyTask = Task.Delay(500).ContinueWith((_) =>
    {
        // this gets executed when the dialog is visible
        SendKeys.Send("C:\\Images\\CCPhotoID.jpg" + "{ENTER}");
    }, TaskScheduler.FromCurrentSynchronizationContext());

    file.InvokeMember("Click"); // this shows up the dialog

    await sendKeyTask;

    // delay continuation to let the Choose File dialog hide
    await Task.Delay(500); 
}

async Task Populate()
{
    var elements = webBrowser.Document.GetElementsByTagName("input");
    foreach (HtmlElement file in elements)
    {
        if (file.GetAttribute("name") == "file")
        {
            file.Focus();
            await PopulateInputFile(file);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

IMO,这种方法对于UI自动化脚本非常方便.你可以Populate像这样打电话,例如:

void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    this.webBrowser.DocumentCompleted -= webBrowser_DocumentCompleted;
    Populate().ContinueWith((_) =>
    {
        MessageBox.Show("Form populated!");
    }, TaskScheduler.FromCurrentSynchronizationContext());
}
Run Code Online (Sandbox Code Playgroud)