Reputation: 91
<input type="button" class="button white-button custom-modal-button" id="btnAttachment" ng-click="openAttachment()" value="Import CSV template">
enter code here
WebElement browse =driver.findElement(By.xpath("//*[@id=\"btnAttachment\"]"));
//pass the path of the file to be uploaded using Sendkeys method
browse.sendKeys("\\Users\\nilaapps13\\Desktop\\lead.csv");
when using sendkeys function it opens up the upload window , but not choosing the file . is there any other way?
Upvotes: 0
Views: 733
Reputation: 91
File file = new File("/users/chennai4/downloads/lead.csv");
StringSelection stringSelection= new StringSelection(file.getAbsolutePath());
//Copy to clipboard
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
Robot robot = new Robot();
// Cmd + Tab is needed since it launches a Java app and the browser looses focus
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_META);
robot.keyRelease(KeyEvent.VK_TAB);
robot.delay(500);
//Open Goto window
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_G);
robot.keyRelease(KeyEvent.VK_META);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_G);
//Paste the clipboard value
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_META);
robot.keyRelease(KeyEvent.VK_V);
//Press Enter key to close the Goto window and Upload window
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.delay(1000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
this is the code i used working perfectly in mac os..
Upvotes: 1
Reputation: 257
the upload window is a Windows popup and not browser popup so selenium commands dont work in this case.
You can make use of java Robot and StringSelection class. Step 1: copy file path to system clipboard Step 2: paste file path to upload window (send keys Ctrl+V) and then send Enter key.
add following packages
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
use StringSelection class for copy and paste operations.
StringSelection stringSelection = new StringSelection("\\Users\\nilaapps13\\Desktop\\lead.csv");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
use Robot class to send keyboard events
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);
Upvotes: 0