How to download file in Selenium
Many times you need to download a file like MS Excel file, MS Word File, Zip file, PDF file, CSV file, Text file, etc.So we need to follow some steps. Manually when we click on link to download file, It will show us dialogue to save file.
Generally this dialog box is in Firefox Browser.Manually just we have to click on save file and then file will be download on particular location.But How Selenium Webdriver works
Selenium Webdriver do not have any feature to handle this save file dialogue.But Selenium can handle this dialog box and we can download any file Webdriver's has Inbuilt class FirefoxProfile and some methods.By using some methods of FirefoxProfile we can download file.
![]() |
| Firefox profile methods |
Before downloading a file in Firefox browser we should know MIME type of that file.Generally we use Mime type here
//profile.setPreference("browser.helperApps.neverAsk.saveToDisk","SpecifyMIME TYPE HERE");
If file is of pdf file then write MIME Type is application/pdf
If you have any file first find out MIME type of your file from here.Even you can google for your MIME TYPE if you don't find here.
"text/plain;" //MIME types Of text File.
"text/csv"); //MIME types Of CSV File.
Here is the code for Download File
package demodownloadfile;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class Downloading_File {
public static void main(String[] args) {
//Create firefox profile
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
//profile.setPreference("browser.download.dir","Specify your directory path here");
profile.setPreference("browser.download.dir","E:\\downloadfile");
//Set path where you want to download file
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword,application/x-rar-compressed,application/octet-stream,application/csv,text/csv");
//Here i have explained some MIME type
WebDriver driver = new FirefoxDriver(profile);
driver.get("http://www.winzip.com/landing/open-rar-file.html");
//Go to url
driver.findElement(By.xpath("//*[@id='downloadlink']/img")).click();
//click on file link and download file
}}
//Now your File has been Downloaded

















