How to upload file in Selenium with Robot class and StringSelection?

Robot class is the magic in Java and it becomes magnetic when it is integrated with Selenium WebDriver. In our earlier tutorials, we have discussed a lot about Robot class to satisfy the different purposes in test automation. Today we are going to discuss the uses of Robot class in Selenium to upload file at runtime.

We come across various scenarios where we need to upload different types of files which contains a various set of testing configurations or macros. Thus, we will discuss the technique to handle such test scenarios in Selenium using Robot class. But, before we jump to the tutorial, I will recommend some of the awesome tutorials for you, which may help you in some test situations while working with Test automation project.

What is StringSelection class in Java?

StringSelection is a Java class which creates an object which is capable to transfer the specified string in plain text to the clipboard.

How does Robot class work with StringSelection class to upload file at runtime in Selenium?

We use StringSelection class along with Robot class to upload file at runtime while performing test automation using Selenium WebDriver. Here we only use robot class for keyboard interaction which mainly pastes file name to the upload file window, whereas, StringSelection class copies the String file name and convert it to the transferrable plain text format. Here it is used to transfer the plain text to the new window which we technically call it as clipboard in Java AWT.

Upload file in Selenium WebDriver

How to implement StringSelection to transfer plain text to the clipboard?

StringSelection mainly converts the String file name to a format or object which can be easily transferred to the file upload window which we get on clicking “Choose File” button of any website. At first, we need to import the following files in our program:

In the next step, we need to implement it. Below code, sample acts like copying file name which is exactly like pressing CTRL+C.

How to implement Robot class to paste copied file name to the file upload window (clipboard)?

Once we copied file name to the clipboard then we use Robot class to implement keyboard actions such as pressing Enter and CTRL+V to the clipboard. Here is the Robot class implementation of CTRL+V.

How to implement upload file functionality in Selenium WebDriver project?

We have seen the implementation of copying file name and pasting it to the file upload window. Let’s take a scenario in which we open a site wherein we need to upload some file with few details.

Application under Test:

Here is the implementation.

This was all about understanding upload file at runtime scenario in Selenium. You can post your queries in a comment below and you can join our Facebook group for the latest updates.

Join Inviul fb group


Leave a Reply