Thursday 3 September 2015

File upload – Selenium WebDriver



There are different ways to upload file, below you can see code for same.

File upload using sendKeys

If   input type="file"  is used the you can upload file using  sendKeys
Suppose “FileUpload.txt” is file you want to upload, and say file is under your project only

 File file = new File("FileUpload.txt ");  
 WebElement upload = driver.findElement(By.locator(LocatorValue));  
 upload.sendKeys(file.getAbsolutePath());  



File upload using Robot


You can upload file using robot framework as below

 File file = new File("FileUpload.txt");  
 WebElement upload = driver.findElement(By.locator(LocatorValue));  
 upload.click();  
 StringSelection filepath = new StringSelection(file.getAbsolutePath());  
 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(filepath, null);  
   
 //imitate mouse events like ENTER, CTRL+C, CTRL+V  
 Robot robot = new Robot();  
 robot.delay(1000);  
   
 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(1000);  
   



You can also upload file using AutoIT tool


 

No comments:

Post a Comment