Reputation: 149
I have a HTML page with button named "Upload" and id: btn-import-questions
. The element:
<button class="btn btn-success btn-sm col-lg-11" id="btn-import-questions" data-ts-file-selector="questions-import-init"> Upload <i class="fa fa-upload"></i></button>
I tried a Selenium Java code like this:
driver.findElement(By.id("btn-import-questions")).sendkeys("C:/path/to/file.xlsx");
But since this is an upload button and not an input-type element, the above code is not working.
Upvotes: 9
Views: 22272
Reputation: 310
This one works for me:
String CSVFile = "C:\\D\\Projects\\file.csv";
WebElement fileElement=this.driver.findElement(By.xpath("//[text()='fileElement']"));
this.wait.until(ExpectedConditions.elementToBeClickable(fileElement ));
fileElement .click();
StringSelection ss = new StringSelection(CSVFile);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//native key strokes for CTRL, V and ENTER keys
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: 2
Reputation: 49
You can use AutoIT tool to do this. Use below code in AutoIT .Au3 file to upload.
sleep(1000)
If WinExists("[TITLE:Open]") Then
Local $hWnd = WinWaitActive ("[TITLE:Open]", "",15)
WinActivate($hWnd)
;WinWaitActive("Open", "", 10)
ControlFocus("Open","","Edit1")
ControlsetText("Open","","Edit1",$CmdLine[1])
ControlClick("Open","","Button1")
ElseIf WinExists("[TITLE:File Upload]") Then
Local $hWnd = WinWaitActive ("[TITLE:File Upload]", "",15)
WinActivate($hWnd)
;WinWaitActive("Open", "", 10)
ControlFocus("File Upload","","Edit1")
ControlsetText("File Upload","","Edit1",$CmdLine[1])
ControlClick("File Upload","","Button1")
Else
Local $hWnd = WinWaitActive ("[TITLE:Choose File to Upload]", "",15)
WinActivate($hWnd)
;WinWaitActive("Open", "", 10)
ControlFocus("Choose File to Upload","","Edit1")
ControlsetText("Choose File to Upload","","Edit1",$CmdLine[1])
ControlClick("Choose File to Upload","","Button1")
EndIf
And then use below code in you C# code to invoke it.
String sExe=(<EXE file path>+" "+<Upload file path>);
Runtime.getRuntime().exec(sExe);
Thread.sleep(5000);
Upvotes: -1
Reputation: 463
Check the DOM because somewhere there must be an <input type="file">
. The website's javascript will call the .click() of this element to pop up the file selector dialog and closing the dialog with a selection will provide the path. With Selenium the same can be achieved with the .sendkeys():
driver.findElement(By.xpath("//input[@type=\"file\"]")).sendkeys(localFilePath);
Upvotes: 8
Reputation: 474271
You are doing it almost correctly, except that sendKeys()
should be called on the input with type="file"
that is, most likely invisible in your case. If this is the case, make the element visible first:
Upvotes: 3