Created
September 30, 2021 08:35
-
-
Save JunilJacob/85aa0ab34fed16c99ac96d61d851cfd2 to your computer and use it in GitHub Desktop.
Upload Files in Selenium for different OS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package utility; | |
import java.awt.*; | |
import java.awt.datatransfer.StringSelection; | |
import java.awt.event.KeyEvent; | |
import org.apache.commons.lang3.SystemUtils; | |
import org.openqa.selenium.WebElement; | |
public class CommonUtils { | |
public static void uploadFile(WebElement uploadBtn, String filelocation) { | |
try { | |
if (SystemUtils.IS_OS_LINUX) { | |
uploadBtn.sendKeys(filelocation); | |
} else if (SystemUtils.IS_OS_MAC) { | |
setClipboardData(filelocation); | |
Robot robot = new Robot(); | |
robot.delay(4000); | |
System.out.println("Open Goto window"); | |
//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); | |
System.out.println("Paste the clipboard value"); | |
//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 | |
System.out.println("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); | |
} else { | |
setClipboardData(filelocation); | |
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); | |
} | |
} catch (Exception exp) { | |
exp.printStackTrace(); | |
} | |
} | |
public static void setClipboardData(String string) { | |
System.out.println(string); | |
StringSelection stringSelection = new StringSelection(string); | |
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment