简体   繁体   中英

Upload file using webdriver

I have tried to upload a photo using the code

driver.findElement(By.xpath("xpath")).sendKeys("C:\\Users\\path\\ben.jpg");

But the image is not getting uploaded.

The html of the upload button is

<button id="upfile1" class="buttonclass" style="cursor: pointer" type="button"> Choose Photo</button>

Is there any other way to upload image. I have tried using WebElement also. I need a solution in JAVA.

I was able to do it using

driver.findElement(By.id("upfile1")).click();
    Thread.sleep(2000);
    StringSelection ss = new StringSelection("C:\\Users\\logo1.jpg");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

But is there any other simple methods to achieve the same other than using robot?

Add System.Windows.Forms reference and try the below code.

driver.findElement(By.Id("upfile1")).Click();
System.Windows.Forms.SendKeys.SendWait("C:\\Users\\path\\ben.jpg");
System.Windows.Forms.SendKeys.SendWait("{ENTER}");

出现的弹出窗口是一个Windows窗口,应使用AutoIT处理。

If you are using RemoteWebDriver , then you need to use LocalFileDector to upload the file to the remote selenium server first. And then use the remote path to upload from the remote selenium server.

driver.setFileDetector(new LocalFileDetector());
driver.findElement(By.xpath("xpath")).sendKeys("C:\\Users\\path\\ben.jpg");

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