Using Selenium to imitate dragging a file onto an upload element

后端 未结 4 681
轻奢々
轻奢々 2020-12-05 10:47

I have a web page that opens a div when you click a button. This div allows you to drag a file from your desktop onto its area; the file then gets uploaded to the server. I\

4条回答
  •  余生分开走
    2020-12-05 11:37

    As @Shmoopy asked for it, here's a C# translation of the code provided by @micred

    private void DropImage(string dropBoxId, string filePath)
    {
       var javascriptDriver = this.Driver as IJavaScriptExecutor;
       var inputId = dropBoxId + "FileUpload";
    
       // append input to HTML to add file path
       javascriptDriver.ExecuteScript(inputId + " = window.$('').attr({type:'file'}).appendTo('body');");
       this.Driver.FindElement(By.Id(inputId)).SendKeys(filePath);
    
       // fire mock event pointing to inserted file path
       javascriptDriver.ExecuteScript("e = $.Event('drop'); e.originalEvent = {dataTransfer : { files : " + inputId + ".get(0).files } }; $('#" + dropBoxId + "').trigger(e);");
    }
    

提交回复
热议问题