File upload in Selenium can be automated using the sendKeys() method. Instead of interacting with the operating system’s file chooser dialog, Selenium directly sends the absolute path of the file to the <input type="file"> element. Once the file path is associated with the Choose File field, clicking the Submit or Upload button uploads the selected file successfully.
For automation demo page use the link follows: Browser Automation Demo: File Upload Form
Below are Selenium scripts in Java, C#, and JavaScript that demonstrate how to associate a file with a file upload field using the sendKeys() method.
Upload file in Selenium
-
Java
-
C#
-
JavaScript
package tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class FileUploadTest {
WebDriver driver = null;
@Test
public void uploadFile() {
driver = new ChromeDriver();
driver.get("https://www.testingtalkslatest.com/browser-automation-demo-file-upload-form/");
WebElement elem = driver.findElement(By.id("fileName"));
elem .sendKeys("C:\Users\Bhaskar\Documents\sample.pdf");
driver.quit();
}
}
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
namespace Tests
{
public class FileUploadTest
{
IWebDriver driver;
[Test]
public void UploadFile()
{
driver = new ChromeDriver();
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("https://www.testingtalkslatest.com/browser-automation-demo-file-upload-form/");
IWebElement elem = driver.FindElement(By.Id("fileName"));
elem.SendKeys(@"C:\Users\Bhaskar\Documents\sample.pdf");
driver.Quit();
}
}
}
const { Builder, By } = require("selenium-webdriver");
(async function uploadFile() {
let driver = await new Builder()
.forBrowser("chrome")
.build();
try {
await driver.get("https://www.testingtalkslatest.com/browser-automation-demo-file-upload-form/");
let elem = await driver.findElement(By.id("fileName"));
await elem.sendKeys("C:\\Users\\Bhaskar\\Documents\\sample.pdf");
} finally {
await driver.quit();
}
})();
Watch YouTube short video here: How to upload file in Selenium?
Great content! Keep up the good work!
Thank you very much ExoWatts.