Notifications
Clear all

[Solved] how to upload a file using selenium

2 Posts
2 Users
5 Reactions
1,031 Views
3
Topic starter

How can I upload a csv-file through the UI using selenium?

 image 1
2 Answers
3
Topic starter

You can't access native controls with Selenium. But one trick you can use is to launch the file upload dialog using selenium, then use java.awt utilities to load a string into the clipboard and invoke the keystrokes to paste it.

import java.awt.Toolkit;
import java.awt.Robot;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

...

CommandCenter cc = CommandCenter.login("CustomerATransMgr");
cc.openTabFromMenu("Tools", "Upload", "Partner");

WebElement input = cc.getUIContext().waitUntilElementExists(By.name("dataFile"));
new Actions(cc.getDriver()).doubleClick(input).build().perform();
Thread.sleep(1000); // we have no choice here but to wait a moment for the popup to open

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection("C:\Temp\myFile.txt"), null);
Robot robot = new Robot();
// Paste filename 
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
// Hit "enter" to accept
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
1

We had some issues with awt approach. Thanks to Yusuf, he came up with following logic.

@Test
public void testEnterpriseUpload() throws Exception {
  Tab tab = cc.openTabFromMenu("Uploads", "Upload Onboard Requests");
  tab.select();
  context.waitUntilUnmask();
  WebElement input = cc.getUIContext().waitUntilElementExists(By.name("dataFile"));
  String datasetDir = new TestEnv().getInstallRootDir().toString();
  String fileLocation = datasetDir+File.separator+"..\\dataset\\CommunityMasterData_dataset"+File.separator+"xml"+File.separator+"EReq.csv";
  input.sendKeys(fileLocation);
  ((JavascriptExecutor) context.getDriver()).executeScript("submitFn();");
}