Selenium: How to upload file using Robot

By: Slav Kurochkin

When you have desktop system prompt box for uploading file on the web, there is nothing you could do with Selenium, since it is become desktop interaction and not a web anymore. Here is a simple solution how to upload file in that case:


 public static void fileUpload() {
        
      
        StringSelection filePath = new StringSelection(your_file_path);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(filePath, 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);
        } catch (Exception exp) {
            exp.printStackTrace();
        }
    }
View Comments

Leave a Comment

Use markdown or basic HTML and be nice.