How to Verify File Download in Selenium WebDriver Java

Profile picture for user devraj

Once you click on the download button, it is essential to verify that the file is downloaded successfully and that we are reading data of the recently downloaded file, not the previous one. This article will discuss how to check several things while downloading the file.

Table of Contents

  1. Test Method
  2. Verify Download Method
  3. Delete File After Download
  4. Clean Directory
  5. Video Tutorial

Test Method

@Test
public void fileDownload() throws InterruptedException, IOException
{
    driver.get("http://autopract.com/selenium/download.html");
    driver.findElement(By.cssSelector("#download")).click();
    Assert.assertTrue(FileUtil.isFileDownloaded("sample", "csv", 5000));
}

Verify Download Method

public static boolean isFileDownloaded(String expectedFileName, String fileExtension, int timeOut) throws IOException 
{
    // Download Folder Path
    String folderName = System.getProperty("user.dir") + File.separator + "downloads";
		
    // Array to Store List of Files in Directory
    File[] listOfFiles;
		
    // Store File Name
    String fileName;   
        
    //  Consider file is not downloaded
    boolean fileDownloaded = false;      
        
    // capture time before looking for files in directory
    // last modified time of previous files will always less than start time
    // this is basically to ignore previous downloaded files
    long startTime = Instant.now().toEpochMilli();
        
    // Time to wait for download to finish
    long waitTime = startTime + timeOut;
       
    // while current time is less than wait time
    while (Instant.now().toEpochMilli() < waitTime) 
    {			
        // get all the files of the folder
        listOfFiles = new File(folderName).listFiles();
            
        // iterate through each file
        for (File file : listOfFiles) 
        {
            // get the name of the current file
            fileName = file.getName().toLowerCase();
        		
            // condition 1 - Last Modified Time > Start Time
            // condition 2 - till the time file is completely downloaded extension will be crdownload
            // Condition 3 - Current File name contains expected Text
            // Condition 4 - Current File name contains expected extension
            if (file.lastModified() > startTime && !fileName.contains("crdownload") &&   fileName.contains(expectedFileName.toLowerCase()) && fileName.contains(fileExtension.toLowerCase())) 
           {
               // File Found
               fileDownloaded = true;
               break;
           }
        }
        // File Found Break While Loop
         if (fileDownloaded) 
             break;
    }
    // File Not Found
    return fileDownloaded;
}

Delete File After Download

To delete the file once the file is found, you can use the delete() method.

if (file.lastModified() > startTime && !fileName.contains("crdownload") && fileName.contains(expectedFileName.toLowerCase()) && fileName.contains(fileExtension.toLowerCase())) 
{
    // File Found
    fileDownloaded = true;
    file.delete();
    break;
}

Clean Directory

You can also use the Apache Common IO File Utils clean Directory method to delete the directory's content. 

FileUtils.cleanDirectory(new File(Constants.DOWNLOAD_DIRECTORY)); 

Video Tutorial: How to Verify File Download in Selenium WebDriver Java

Comments

Hi, 

I want to download excel file to a particular folder. Its working but with the original file, a corrupted file with preceding $ also gets download. Please help me to prevent this corrupted file download.

Hi,

To prevent the file with the preceding $, you can use this:

File directory = new File("C:\\Users\\arili
\\git\\Assignments\\Selenium\\target");
[] files = directory.listFiles();

for (File f : files) {
    if (f.getName().contains("$")) {
    f.delete();
}

This iterate over the directory and when you specify the $. It will delete any filename with the preceding $ using the delete() method from files.

Hi, should you repost your video (5. Video Turtorial)? I can't find this video so I can't apply it on my project (I'm a newbie in Automation Testing). 

or should you send this video to dinhmanh.dsn@gmail.com? 

Thanks a lot