Uploading Multiple files through Selenium
In this article, we are going to see how to upload multiple files with the help of Selenium, which is a super easy way. There are other ways that involve triggering the file selection dialog, providing a path, and then mimicking copy(Ctrl + C) and paste(Ctrl + V) behavior. But doing that makes the code a bit complex and adds a lot of lines to it. In this example, we are using Chrome web driver, but the same could run with any other driver as well.
Let’s get started with our code.
Pom dependency
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.1.4</version> </dependency>
We need to locate an html tag with
<input type="file">
And we need to start sending keys to it. In the below code we have the paths of the files that we need to set, so we just run through the for loop and set every path into WebElement which corresponds to type=”file” .
For multiple upload, the html tag should have a multiple attribute. The same code works for single file upload also, just call it once!
public static void performUploads(WebDriver driver) { // <input type="file"> WebElement multiFileInput = driver.findElement(By.id("fileToUpload")); List<String> filePaths = new ArrayList<>(); for (String path : filePaths) { multiFileInput.sendKeys(path); } // Here you can perform the rest of the actions like form submission. }
Keep Learning! Stay Sharp!