简体   繁体   中英

How do I upload a file from local to a webapp using webdriver with java?

I have to import an Excel file to a web application. To import 1st I have to click on an import btn, which will pop open another window that has the browse btn. Clicking on the browsebtn opens a OS dialogue box. I want to send the file path in this dialogue box then select the file and click upload. here is the code I am using for this:

String path="C:/excelFiles";
Robot robot;

WebDriverWait wait=new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOf(importExcelbtn));
importExcelbtn.click();
browseBtn.sendKeys(path);
wait(4);
browseBtn.click();

wait(4);


StringSelection sel=new StringSelection(excelFileToImport);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel,null);

System.out.println("File to upload:"+ sel);
robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
wait(3);            
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
okBtn.click();
} catch (AWTException e) {
e.printStackTrace();
}

The problem is, my code opens all the window, but it does not/cannot put the correct file path in the OS dialogue box so eventually the test fails. Please help.

After Clicking Import Button add this code. One more question, After modal dialog opens which button is focused like open/Cancel. Add a screenshot of modal dialog for better answer.

     setClipboardData("C:\\excelFiles");
     Robot robot = new Robot(); 
     robot.keyPress(KeyEvent.VK_CONTROL);
     robot.keyPress(KeyEvent.VK_V);
     robot.keyRelease(KeyEvent.VK_V);
     robot.keyRelease(KeyEvent.VK_CONTROL);
     robot.keyPress(KeyEvent.VK_ENTER);
     robot.keyRelease(KeyEvent.VK_ENTER);
     robot.delay(5000);

     public static void setClipboardData(String string) 
    {
       StringSelection StrSelect = new StringSelection(string);
       Toolkit.getDefaultToolkit().getSystemClipboard().setContents(StrSelect, null);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM