How To Upload a File with Selenium

It is very common functionality to upload a file to the webserver. But when it involves in automating you get a dialog box that is just out of reach for selenium.

In selenium to achieve this functionality people use AutoIt a third party tool to manipulate the dialog box but one major disadvantage of AutoIt works only with windows limiting your ability to test this functionality on different browser & operating system combinations.

A work-around for this problem is to side-step the system dialog box entirely. We can do this by using Selenium to insert the full path of the file we want to upload (as text) into the form and then submit the form.

package org.npntraining.hands_on;
import io.github.bonigarcia.wdm.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;
import org.testng.*;
import org.testng.annotations.*;
import java.io.*;
public class FileUpload {
    @Test
    public void uploadFile() throws Exception {
        WebDriverManager.firefoxdriver().setup();
        WebDriver driver = new FirefoxDriver();
        driver.get("http://the-internet.herokuapp.com/upload");
        String filename = "d:/Dockerfile.txt";
        File file = new File(filename);
        String path = file.getAbsolutePath();
        driver.get("http://the-internet.herokuapp.com/upload");
        driver.findElement(By.id("file-upload")).sendKeys(path);
        driver.findElement(By.id("file-submit")).click();
        String text = driver.findElement(By.id("uploaded-files")).getText();
        Assert.assertEquals(text, file.getName());
    }
}

This approach will work across all browsers

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *