In this article, we will learn how to handle file uploads and downloads.
Uploading Files
To Upload files, we will use http://the-internet.herokuapp.com/upload as our test application. Through this site any user can upload files without requiring them to sign up.
In Selenium Webdriver we can Upload files by simply using the method sendKeys() on the select file input field to enter the path to the file to upload.
Let’s create a test case in which we will automate the following scenarios to handle File-Upload:
- Invoke a Google chrome browser.
- Open URL: http://the-internet.herokuapp.com/upload
- Click on Choose file to upload a file.
- Click on Upload button
Now, we will create a test case step by step in order to understand of how to handle file-upload in WebDriver.
Step 1: Launch Eclipse IDE.
Step 2: Go to File > New > Click on Java Project.
Enter Project Name: Demo_FileUpload
Step 3: Right click on the Project Name and click on the New > class.
Give your Class name as “Test_Fileupload” and Select the checkbox “public static void main(String[] args) and click on “Finish” button.
Step 4: Invoke the Google Chrome browser and set the system property to the path of your chromedriver.exe file.
[box type="info" align="" class="" width=""]Here is the sample code to set Chrome driver system property:
// System Property for Chrome Driver  Â
 System.setProperty("webdriver.chrome.driver", “ D:\\Drivers\\geckodriver.exe "); [/box]
After that we have to initialize the Chrome driver using ChromeDriver Class. Below is the sample code to initialize Chrome driver using ChromeDriver class.
[box type="info" align="" class="" width=""]// Instantiate a ChromeDriver class.     Â
WebDriver driver=new ChromeDriver();Â [/box]
We will get the below code to launch Google Chrome browser after combining both of the above codes.
[box type="info" align="" class="" width=""]System.setProperty("webdriver.chrome.driver", “ D:\\Drivers\\geckodriver.exe "); Â
WebDriver driver=new ChromeDriver();[/box]
After that, we need to navigate to the desired URL.
Below is the sample code to navigate to the desired URL:
[box type="info" align="" class="" width=""]// Launch Website Â
driver.navigate().to("http://the-internet.herokuapp.com/upload"); [/box]
Here is the complete code for above scenario:
import org.openqa.selenium.WebDriver;Â Â
import org.openqa.selenium.chrome.ChromeDriver;Â Â
 Â
public class Test_Fileupload {Â Â
 Â
    public static void main(String[] args) { Â
         Â
        // System Property for Chrome Driver  Â
 System.setProperty("webdriver.chrome.driver", “ D:\\Drivers\\geckodriver.exe "); Â
 Â
    String baseUrl = ("http://the-internet.herokuapp.com/upload"); Â
    WebDriver driver=new ChromeDriver(); Â
 Â
     driver.get(baseUrl);
    }   Â
}Â