Manoj NN
Manoj NN

Reputation: 1

How to automate file upload in chrome using selenium?

On an Ubuntu machine I try to automate file upload but I am unable to do so in Chrome using selenium. I tried with Robot class and normal send keys method.

Please refer my code:

StringSelection select = new StringSelection("/home/manojnn/Desktop/OrderDetails.xlsx"); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(select,null);

     System.out.println("selection" +select);
     driver.findElement(By.xpath("//label[text()='Upload']")).click();
    Thread.sleep(3000);
    Robot robot = new Robot();
     Thread.sleep(1000);

      // Press Enter
     robot.keyPress(KeyEvent.VK_ENTER);

    // Release Enter
     robot.keyRelease(KeyEvent.VK_ENTER);

      // Press CTRL+V
     robot.keyPress(KeyEvent.VK_CONTROL);
     robot.keyPress(KeyEvent.VK_V);

    // Release CTRL+V
     robot.keyRelease(KeyEvent.VK_CONTROL);
     robot.keyRelease(KeyEvent.VK_V);
     Thread.sleep(1000);


     robot.keyPress(KeyEvent.VK_ENTER);
     robot.keyRelease(KeyEvent.VK_ENTER);

Upvotes: 0

Views: 7554

Answers (3)

Ruchi Dhole
Ruchi Dhole

Reputation: 95

You can use the external tool like AUTOIT and can use it with selenium for upload purpose. Try this link https://www.seleniumeasy.com/selenium-tutorials/upload-a-file-using-selenium-webdriver-with-autoit

Upvotes: 1

Andersson
Andersson

Reputation: 52665

You don't need to click on upload button and handle upload prompt, but just to send path to file to appropriate input field. Try following solution and let me know if it not works:

driver.findElement(By.xpath('//input[@type="file"]')).sendKeys("/home/manojnn/Desktop/OrderDetails.xlsx"); 

Upvotes: 3

Umesh Kumar
Umesh Kumar

Reputation: 1397

for file upload you need to do directly pass file path on the uploadfile text field. use beloe driver.findElement(By.xpath(uploadTextFiledElementId)).sendKeys("filepath");

Upvotes: -1

Related Questions