Customize the name of file going to be downloaded?

please discribe with code.
by (171 points)
Are you looking for specific browser?
by (324 points)
Yes, For 'Chrome' and 'Firefox' browser.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

1 Answer

by (171 points)
0 votes

This is divided into two parts, 1. Download the file 2. Change the file name.

To download the file using Chrome, you can use below code.

String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
options.setExperimentalOptions("prefs", chromePrefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);
To download file using Firefox, you can use below code
FirefoxProfile fprofile= new FirefoxProfile();
fprofile.setPreference("browser.download.folderList",2);  //0-desktop,1-file download folder,2-specified location
fprofile.setPreference("browser.download.manager.showWhenStarting", false); //prevent download file window
fprofile.setPreference("browser.download.manager.focusWhenStarting", false);
fprofile.setPreference("browser.download.manager.alertOnExeOpen", false); //prevent from opening a file
cap.setCapability(FirefoxDriver.PROFILE, fprofile);
WebDriver driver=new FirefoxDriver(cap);

Once files are downloaded to your local machine, you can change the name of the file.

File oldfile =new File("oldfile.ext");
File newfile =new File("newfile.ext");
System.out.println("Not renamed");

Renaming of file will work only if you are executing tests on local machine, to change file name on the remote machine, you will have to implement FTP server  and create FTP client to make changes.

Hope that helps!