Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload files to site automatically without browser focus

I work on test script to automate file uploading to a site and execute script in headless mode. It needs to upload list of files one by one, I develop it based on Selenium WebDriver. I use AutoIT script to handle dialog window, file chooser window. Parameter $CmdLine[1] contains the path of actual file.

ControlFocus("Open a file","","Edit1")
ControlSetText("Open a file","","Edit1", $CmdLine[1])
ControlClick("Open a file","","Button1")

It is executed with this code:

Runtime.getRuntime().exec(autoITExecutable);

It opens dialog window, so it can't work without focus on browser window. java.awt.Robot class works similar, it needs focus on browser window.

I tried to use sendKeys() method too, but input field is unable to handle file in this way. Katalon Studio is also unable to handle this field.

Example sites with similar forms:

http://ajaxuploader.com/demo/simple-upload.aspx

https://ec.europa.eu/cefdigital/DSS/webapp-demo/validation

https://tus.io/demo.html

like image 262
plaidshirt Avatar asked Oct 18 '18 11:10

plaidshirt


2 Answers

You can try the following code:

// wait for the window to appear
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());

// switch to the file upload window
Alert alert = driver.switchTo().alert();

// enter the filename
alert.sendKeys(fileName);

// hit enter
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);

// switch back
driver.switchTo().activeElement();
like image 168
PassionateCoder Avatar answered Sep 21 '22 02:09

PassionateCoder


Try this one,

webElement.sendKeys(System.getProperty("user.dir") + "file path");

Here,

  • webElement is your element identified for file upload. Please make sure that the input element is visible.
  • try to specify file path as relative path of the content that we want to upload.

Make sure, you are not clicking on the browse button, clicking on browse button will open windows dialogue box where selenium webDriver will won't work.

like image 38
Manju Avatar answered Sep 24 '22 02:09

Manju