title: One solution for File Upload using Java Robot API with Selenium WebDriver by Java
body: <p>I saw that lots of people have Problems uploading a file in a test Environment with Selenium WebDriver. I use the selenium WebDriver and java, and had the same problem. I finally have found a solution, so i will post it here hoping that it helps someone else.</p>
  
  <p>When i need to upload a file in a test, i click with Webdriver in the button and wait for the window "Open" to pop. And then i copy the path to the file in the clipboard and then paste it in the "open" window and click "Enter". This is working because when the window "open" pops up, the focus is always in the "open" button.</p>
  
  <p>You will need these classes and method:</p>
  
  <pre><code>import java.awt.Robot;
  import java.awt.event.KeyEvent;
  import java.awt.Toolkit;
  import java.awt.datatransfer.StringSelection;
  
  
  public static void setClipboardData(String string) {
     StringSelection stringSelection = new StringSelection(string);
     Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
  }
  </code></pre>
  
  <p>And that is what i do, just after opening the "open" window:</p>
  
  <pre><code>setClipboardData("C:\\path to file\\example.jpg");
  //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);
  </code></pre>
  
  <p>And that´s it. It is working for me, i hope it works for some of you.</p>