How To Download & Upload Files Using Selenium With Java
Tags: java, opensource, coding, api
Published: 2020-04-07 11:07:18

---
title: How To Download & Upload Files Using Selenium With Java
published: true
description: While Selenium testing you may have come across a requirement where you need to either download or upload file in Selenium. Almost every web-application over
tags: java, opensource, coding, api
canonical_url: https://www.lambdatest.com/blog/how-to-download-upload-files-using-selenium-with-java/
cover_image: https://www.lambdatest.com/blog/wp-content/uploads/2020/02/Selenium-WebDriver-Java.jpg
---

While [Selenium](https://www.lambdatest.com/selenium?utm_source=devto&utm_medium=organic&utm_campaign=sep14_rd&utm_term=rd&utm_content=webpage) testing you may have come across a requirement where you need to either download or upload file in Selenium. Almost every web-application over the internet may have a feature for allowing users to either download or upload a file. Be it a rich-media platform such as YouTube which lets you upload video files or online photo collage maker, or an e-commerce web application which allows you to upload images. Even writing assistants like Grammarly and Plagiarism checker like Quetext offer an uploading file functionality. Similarly, these websites offer downloading functionality too. YouTube allows offline downloading, e-commerce platforms such as Amazon will let you download the invoices of your orders. My point being is that if you are an automation tester who has a routine set around Selenium testing, there is a good chance for you to run into a requirement where you may have to test a feature around downloading or uploading files in Selenium WebDriver.

In Selenium testing, it is very important to know how to Upload files in Selenium WebDriver or download files in Selenium WebDriver through automation testing with Selenium. In this Selenium Java tutorial, I am going to highlight different ways through which you can download or upload files in Selenium WebDriver.

## What Is A Remote WebDriver?

Remote WebDriver implements each command of JSONWireProtocol and users can perform locally and remotely on a remote server. All Browser Drivers are child class of RemoteWebDriver and RemoteWebDriver is a class type and implements all WebDriver interface. So, RemoteWebDriver has the capability of Selenium testing on either local infrastructure or on a cloud-based [Selenium Grid](https://www.lambdatest.com/selenium-automation) such as LambdaTest.

Let’s understand the real use case of uploading files in Selenium WebDriver. Suppose you are developing automation scripts for testing with Selenium & Java over an online clinical web platform where patients can book a video consultation with a doctor. On that website, there is an option to upload a Test Report where a doctor can review and discuss test reports. In such a case, you need to use upload file concepts to upload reports to their clinical web application.

Note: If you have already implemented file uploading script in your local script and want to upgrade to a remote cloud-based environment then you need to just change WebDriver to RemoteWebDriver and use `driver.setFileDetector(new LocalFileDetector());` method.

***Want to check browser compatibility of [Background clip text](https://www.lambdatest.com/web-technologies/background-clip-text?utm_source=devto&utm_medium=organic&utm_campaign=may31_rd&utm_term=rd&utm_content=web_technologies)? It is a non-standard method of clipping a background image to the foreground text.***

## Upload Files in Selenium With Java

If you are familiar with Selenium 1, Accessible web server and attachFile command were using upload files. And In Selenium 2 onward, It is like just a sendkeys() command and you’re done uploading a file. It is so easy to do that now a day. When you want to upload files locally then you can directly use SendKey() and give a path in code. However, the same thing will not work remotely as did on locally. For uploading files in Selenium Remote WebDriver, you need to leverage the method called the setFileDetector method. That way, Remote WebDriver acknowledges when you are uploading files for Selenium testing over either a local machine or a remote machine. By this excellent feature of Selenium 2, you do not have to write separate code to perform Selenium testing for uploading files over locally or remotely hosted web-application. We have following options to upload files in a Remote Selenium WebDriver:

- SendKeys
- Robot Class
- AutoIT tool
- Jacob API

### Upload Files In Selenium WebDriver Using Sendkeys()

It is always preferred to use first inbuilt features provided by Selenium Java to perform Upload file in Remote Selenium WebDriver. That is the SendKeys method. It directly applies to input tags which have an attribute as type=’file’.

Here is an example to upload files in Selenium and Java using the Sendkeys():

```
WebElement addFile = driver.findElement(By.xpath(".//input[@type='file']"));
addFile.sendKeys("/Users/neeraj.kumar/Desktop/c1.jpeg");
```


### Upload Files In Selenium WebDriver Using Robot Class 

Robot class is an AWT class package in Java. This is also a very good option to choose for Upload file in selenium. This will help to automate windows based Alert or pop up, Print pop up or native windows screen. This is independent of the Operating System.

Here is the example of File uploading using Robot class:

```
public void fileUpload (String path) {
        StringSelection strSelection = new StringSelection(path);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(strSelection, null);
 
        Robot robot = new Robot();
  
        robot.delay(300);
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
        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.delay(200);
        robot.keyRelease(KeyEvent.VK_ENTER);
    }
```
### Upload File In Selenium WebDriver Using AutoIT 

AutoIT is an external automation tool and not provided by the selenium community. Initially, AutoIT was used to automate native windows related pop up, however, there is a drawback of using AutoIT is that it creates .exe file and runs only on Windows. It is not advisable to use AutoIT for File upload. However, if you still wish to perform a file upload in Selenium WebDriver using AutoIT then here is an example for you:

```

WinWaitActive("File Upload"); 
Send("/Users/neeraj.kumar/Desktop/c1.jpeg");    
Send("{ENTER}")
```


**Note:** Save the file with .exe extension and run using command e.g Runtime.getRuntime().exec().

### Upload File using Jacob API

Jacob provides the API technique to perform Upload file using Selenium. Again, to perform a file upload in Selenium WebDriver using Jacob API you would need a .dll file. That means it won’t work for Mac or Linux operating system. If you only want to target Windows operating systems then here is an example of upload File using Jabob API.

```

public void UploadFile() throws InterruptedException {

		String userDir = System.getProperty("user.dir");

FinalString jacobArchitect =
 System.getProperty("sun.arch.data.model").contains("32") ? "jacob-1.18-x86.dll" : "jacob-1.18-x64.dll";
		String jacobArchitectPath = userDir + "\" + jacobArchitect;

		File filejacob = new File(jacobArchitect);
		System.setProperty(LibraryLoader.JACOB_DLL_PATH,
				filejacob.getAbsolutePath());
		AutoItX uploadWin = new AutoItX();

		driver = new FirefoxDriver();
		driver.get(“https://blueimp.github.io/jQuery-File-Upload/
”);

		Thread.sleep(1000);

WebElement addFile = driver.findElement(By.xpath(".//input[@type='file']"));
.click();

		Thread.sleep(1000);

		if (uploadWin.winWaitActive("File Upload", "", 5)) {
			if (uploadWin.winExists("File Upload")) {
				uploadWin.sleep(100);
				uploadWin.send("/Users/neeraj.kumar/Desktop/c1.jpeg");
				uploadWin.controlClick("File Upload", "", "&Open");

			}
		}
	}
```
 
## Let’s Hit The Practical For File Upload In Selenium WebDriver

Now, let me demonstrate how to upload files in a Remote Selenium WebDriver over both, on your local infrastructure as well as over the cloud-based Selenium Grid. As a part of this Selenium Java tutorial, I would be focusing on leveraging the SendKeys() method to upload files in Selenium and Java.

The scenario would be,

- open [https://blueimp.github.io/jQuery-File-Upload/](https://blueimp.github.io/jQuery-File-Upload/) and
- Click on Add files… button
- Then Start Upload
- Assert it back.
 
First off, we will start with the demonstration to upload files using local infrastructure machines. Later we will have a demonstration of the same Selenium testing script over a cloud-based Selenium Grid.

### Upload Files In Selenium WebDriver Over Local Infrastructure

Below is a Selenium Java testing script which demonstrates how to upload files in Selenium WebDriver over your local machine.

```

package com.POMFramework.tests;

import static org.testng.Assert.assertTrue;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class LamdaTestUploadFile {

	private RemoteWebDriver driver;

	@BeforeClass
	public void setUp() throws Exception {

		System.setProperty("webdriver.chrome.driver", "/Users/neeraj.kumar/Desktop/chromedriver");

		driver = new ChromeDriver();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@Test
	public void lamdaTest() throws Exception {
		driver.get("https://blueimp.github.io/jQuery-File-Upload/");
		Thread.sleep(2000);
		WebElement addFile = driver.findElement(By.xpath(".//input[@type='file']"));
		addFile.sendKeys("/Users/neeraj.kumar/Desktop/c1.jpeg");
		
		driver.findElement(By.xpath(".//span[text()='Start upload']")).click();

		Thread.sleep(2000);
		if(driver.findElement(By.xpath(".//a[text()='c1.jpeg']")).isDisplayed()) {
			assertTrue(true, "Image Uploaded");
		}else {
			assertTrue(false, "Image not Uploaded");
		}
	}
	

	@AfterClass
	public void tearDown() throws Exception {
		driver.quit();
	}
}
```
 

That is it.! However, it isn’t all you need to know. It is important to note that when we refer to practical and real-time scenarios the requirement to perform automated browser testing might involve hundreds of browsers + OS combinations to be tested. Not to forget, the desired capabilities are bound to go bigger as your web application would scale over time.

In such scenarios, maintaining an in-house Selenium infrastructure is both time-consuming and expensive. You will need to hire more machines and resources on-board. Unless you can afford a device lab provider such as Amazon AWS which can be costly for many businesses. So what can you do?

Fortunately, there is a cloud-based Selenium Grid such as LambdaTest which will help you execute Selenium testing for you web-application to ensure [cross browser compatibility](https://www.lambdatest.com/feature?utm_source=devto&utm_medium=Blog&utm_campaign=Harshit-07042020&utm_term=Harshit ). With LambdaTest, you can test on 2000+ real browsers & operating systems for both mobile & desktop. That way, you won’t have to worry about maintaining your Selenium Grid as we will provide you with a cloud-based infrastructure with zero downtime, where machines are ready to fire up 24/7, as per your wish.

Want to check browser compatibility of the [background-position-x-y](https://www.lambdatest.com/web-technologies/background-position-x-y?utm_source=devto&utm_medium=organic&utm_campaign=may31_rd&utm_term=rd&utm_content=web_technologies)? This CSS longhand properties helps you to define the x or y positions of the background image separately.

### Upload Files In Selenium WebDriver Over An Online Selenium Grid

Now, the same scenario can be run on the LamdaTest’s online Selenium Grid. You should observe here that we have changed only two points as shown below.

```
driver = new RemoteWebDriver(new URL("http://hub.lambdatest.com:80/wd/hub"), capabilities);
        driver.setFileDetector(new LocalFileDetector());
```
 

And, you are done!!! Here is the full Selenium Java testing script to upload file in Selenium WebDriver over an online Selenium Grid.

```
package com.POMFramework.tests;

import static org.testng.Assert.assertTrue;

import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class LamdaTestUploadFileRemotely {

	private RemoteWebDriver driver;

	@BeforeClass
	public void setUp() throws Exception {

		ChromeOptions capabilities = new ChromeOptions();
		capabilities.setCapability("user","<username>");
		capabilities.setCapability("accessKey","<accesskey>");
		capabilities.setCapability("build", "Build 2");
		capabilities.setCapability("name", "Check Uploaded Image");
		capabilities.setCapability("platformName", "Windows 10");
		capabilities.setCapability("browserName", "Chrome");
		capabilities.setCapability("browserVersion","79.0");
    	
        driver = new RemoteWebDriver(new URL("http://hub.lambdatest.com:80/wd/hub"), capabilities);
        driver.setFileDetector(new LocalFileDetector());
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	
	}

	@Test
	public void lamdaTest() throws Exception {
		driver.get("https://blueimp.github.io/jQuery-File-Upload/");
		Thread.sleep(2000);
		WebElement addFile = driver.findElement(By.xpath(".//input[@type='file']"));
		addFile.sendKeys("/Users/neeraj.kumar/Desktop/c1.jpeg");
		
		driver.findElement(By.xpath(".//span[text()='Start upload']")).click();

		Thread.sleep(2000);
		if(driver.findElement(By.xpath(".//a[text()='c1.jpeg']")).isDisplayed()) {
			assertTrue(true, "Image Uploaded");
		}else {
			assertTrue(false, "Image not Uploaded");
		}
	}
	

	@AfterClass
	public void tearDown() throws Exception {
		driver.quit();
	}
}
```
#### Monitoring Result Over LambdaTest Automation Dashboard

Once you navigate to the automation dashboard on LambdaTest. You will notice that the test has been executed successfully in the **timeline**.

![screenshot_testing](https://cdn.lambdatest.com/blog/wp-content/uploads/2020/02/screenshot_testing.png)

**Automation Logs:** In the Automation Logs you can see each execution in detail including browser version, Operating system version, execution date and time, videos, screenshots and steps of execution.

![automation_logs](https://cdn.lambdatest.com/blog/wp-content/uploads/2020/02/automation_logs-1.png)

With that said, you have learned how to upload files in Remote Selenium WebDriver for both, local and cloud-based Selenium Grid.

## Download Files in Selenium WebDriver

Now, that you are familiar with file uploading in Selenium WebDriver, you might be thinking that downloading a file with Selenium WebDriver is going to be just as easy! Well, think again! You have a web-application and you would want the download file functionality to work seamlessly across different browsers so that your customers aren’t bothered by a UI bug. However, every web browser offers a different UI when downloading a file. Let us look at different screenshots of different browsers running on a macOS.

Mozilla Firefox download screen:

![salesforce_screenshot](https://cdn.lambdatest.com/blog/wp-content/uploads/2020/02/salesforce_screenshot.png)

Safari download screen:

![safari_screenshot](https://cdn.lambdatest.com/blog/wp-content/uploads/2020/02/safari_screenshot.png)

Google Chrome Download screen:

![salesforce_screenshot_testing](https://cdn.lambdatest.com/blog/wp-content/uploads/2020/02/salesforce_screenshot_testing.png)

Similarly, these screenshots would differ for different operating systems, and operating system versions too. So when you are downloading a file through Google Chrome on Windows 7 it might give the below screen.

![salesforce_screenshot_from_chrome](https://cdn.lambdatest.com/blog/wp-content/uploads/2020/02/salesforce_screenshot_from_chrome.png)

As you may notice, here the file was directly downloaded when the timer clocked-down to 0 seconds, without any user confirmation.

So every browser will have a different download mechanism based on the operating system over which it is being utilized. Browser configuration using a profile, different browser, different Operating Systems play a vital role while Selenium testing with Java to download the file.  
To automatically download file using Selenium with Java, we have the following options:

- AutoIT
- Robot Class
- Browser Profile

### Download File In Selenium WebDriver Using AutoIT

Already we have discussed the AutoIT tool. The same tool is used for downloading files in selenium. Again, download window changes as per Browsers. So users have to consider all scenarios to automate download pop up.

Here is AutoIT script example:

```
WinWait("[CLASS:#MozillaDialogClass]","",8)
Send("!s")
Sleep(10000)
Send("{ENTER}")
```
 

Save this code and generate **.exe** file and execute in java code using **Runtime.getRuntime().exec()**. Again, It is not advisable to use it as it supports only Windows operating system and its external tool.

### Download File In Selenium WebDriver Using Robot Class

You can run the below Selenium testing script to download files using Selenium with Java through Robot class.

```

public void fileDownload() {
Robot robot = new Robot(); 
robot.keyPress(KeyEvent.VK_TAB);
		robot.keyRelease(KeyEvent.VK_TAB);
		robot.keyPress(KeyEvent.VK_ENTER); 
		robot.keyRelease(KeyEvent.VK_ENTER);  

    }
```
 

**Note:** AutoIT and Robot class code could change based on the browser-specific profile set as well as where you want to save. Moreover, most important is cursor focus. If your download pop up is not in focus then mostly your code will not work.

### Download File In Selenium WebDriver Using The Browser Profile Setting

By leveraging the browser profile setting, you can download files in Selenium WebDriver without interacting with the download window pop-up. You need to trick the browser profile. Here I have given a below example for Google Chrome browser and Mozilla Firefox browser.

Add this code into your Selenium Java testing suite.

**Google Chrome**

```
System.setProperty("webdriver.chrome.driver", "/Users/neeraj.kumar/Desktop/chromedriver");

ChromeOptions options = new ChromeOptions();
		
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("download.prompt_for_download", false);
options.setExperimentalOption("prefs", prefs);
		
RemoteWebDriver driver = new ChromeDriver(options);
```
 

**Mozilla Firefox**

```

FirefoxProfile profile=new FirefoxProfile();
profile.setPreference("browser.helperApps.neverAsk.openFile", "application/octet-stream");

WebDriver driver=new FirefoxDriver(profile);
```


 
## Let’s Hit The Practical For File Download In Selenium WebDriver

As we did a practical implementation to upload file in Selenium WebDriver. We will now practice downloading files in Selenium WebDriver on both local and cloud-based Selenium Grid. I will be demonstrating the file downloading using the Browser Profile Setting.

Want to check browser compatibility of [CSS3 Border images](https://www.lambdatest.com/web-technologies/border-image?utm_source=devto&utm_medium=organic&utm_campaign=may31_rd&utm_term=rd&utm_content=web_technologies)? Use these border images to create borders with style.

### Download Files Using Selenium With Java With The Browser Profile Setting

```

package com.POMFramework.tests;

import java.awt.AWTException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class LamdaTestDownloadFile {
	
	private RemoteWebDriver driver;

	@BeforeClass
	public void setUp() throws Exception {

		System.setProperty("webdriver.chrome.driver", "/Users/neeraj.kumar/Desktop/chromedriver");

		ChromeOptions options = new ChromeOptions();
		
		Map<String, Object> prefs = new HashMap<String, Object>();
		prefs.put("download.prompt_for_download", false);
		options.setExperimentalOption("prefs", prefs);
		
		driver = new ChromeDriver(options);
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		driver.manage().window().maximize();
	}
	
	@Test
	public void fileDownload() throws AWTException, InterruptedException {
		
		driver.get("https://chromedriver.storage.googleapis.com/index.html?path=79.0.3945.36/");
		Thread.sleep(2000);
		WebElement btnDownload = driver.findElement(By.xpath(".//a[text()='chromedriver_win32.zip']"));
		btnDownload.click();
		
		Thread.sleep(7000);
		
	}

	@AfterClass
	public void tearDown() throws Exception {
		driver.quit();
	}
}
```

**Note:** Working on a local machine for downloading files is easy to handle but on a remote machine, it works based on the permission you have been provided to access the remote WebDrivers.

### Download File Example For Online Selenium Grid With The Browser Profile Setting  

Similar to uploading, the only thing we need to tweak in the Selenium Java testing script is going to be the file detector and the hub URL.

```

package com.POMFramework.tests;

import java.awt.AWTException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class LamdaTestDownloadFileRemotely {

	private RemoteWebDriver driver;

	@BeforeClass
	public void setUp() throws Exception {

		ChromeOptions capabilities = new ChromeOptions();
		capabilities.setCapability("user","<userName>");
		capabilities.setCapability("accessKey","<Access key>");
		capabilities.setCapability("build", "Build 4");
		capabilities.setCapability("name", "Downloading File");
		capabilities.setCapability("platformName", "Windows 10");
		capabilities.setCapability("browserName", "Chrome");
		capabilities.setCapability("browserVersion","79.0");
    	
		
		Map<String, Object> prefs = new HashMap<String, Object>();
		prefs.put("download.prompt_for_download", false);	
		capabilities.setExperimentalOption("prefs", prefs);
		
        driver = new RemoteWebDriver(new URL("http://hub.lambdatest.com:80/wd/hub"), capabilities);
        driver.setFileDetector(new LocalFileDetector());
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	
	}
	
	@Test
	public void fileDownload() throws AWTException, InterruptedException {
		
		driver.get("https://chromedriver.storage.googleapis.com/index.html?path=79.0.3945.36/");
		Thread.sleep(2000);
		WebElement btnDownload = driver.findElement(By.xpath(".//a[text()='chromedriver_win32.zip']"));
		btnDownload.click();
		
		Thread.sleep(10000);
	}
	

	@AfterClass
	public void tearDown() throws Exception {
		driver.quit();
	}
	
}
```
 

Below is a screenshot of LambdaTest automation logs which shows that the file is downloaded successfully.

![test_report](https://cdn.lambdatest.com/blog/wp-content/uploads/2020/02/test_report.png)

## Wrapping Up!

If you have a website where you are allowing users to either download or upload files in Selenium WebDriver then you need to ensure they work seamlessly across all browsers. Selenium testing can help you easily automate the download & upload file functionality of your web-application. Working on upload file feature of Selenium is very easy if you have understood the difference between Remote WebDriver and WebDriver Interface.  
Although Selenium can help you execute test cases in local infrastructure. It is always recommended to go for a cloud-based Selenium Grid in order to save both time and resources. Selenium testing over an online Selenium Grid requires you to tweak a couple of lines of code where you specify the appropriate Hub URL for your Remote WebDriver. Similarly, Download file using a third-party tool would end up having a flaky automation test. Hence, it is always preferred browser profiling settings in order to get a stable script. I hope the practical examples provided for both were explained in great detail and that they helped you gain more insight into the matter. If you still got questions around downloading & uploading files in Selenium WebDriver then make sure to drop them in the comment section. Cheers and happy testing!

[![cross_browser_testing_tool](https://cdn.lambdatest.com/blog/wp-content/uploads/2020/01/Cross-Browser-Testing-Tool-min.jpg)](https://accounts.lambdatest.com/register/?utm_source=devto&utm_medium=Blog&utm_campaign=Harshit-07042020&utm_term=Harshit )