File Download in Playwright




In Playwright, file download refers to the process of handling situations where a web application triggers the downloading of files, such as PDFs, CSVs, images, or reports. Normally, when you click a download button or a link that initiates a file download, the browser prompts to save the file. 

In automated testing, Playwright provides a structured way to handle and verify these downloads without manual intervention.

In Playwright Java, downloading a file involves listening for the Download event and then saving the file locally using the download.saveAs() method.


Here’s the theory behind file download in Playwright:


Download Event:

When an action in the browser (like clicking a button or link) triggers a download, Playwright emits a special download event. This allows the test script to detect that a download has started and then capture details about it.

Download Object:

Playwright represents the file download as a Download object. This object contains metadata such as the file’s suggested name, its URL, and a reference to the temporary storage location where the file is initially kept during the download process.

Temporary Storage:

By default, downloaded files are saved to a temporary location. They are not stored permanently until the script explicitly saves them. This ensures tests don’t clutter the file system unless the user specifically chooses to persist the files.

File Path Control:

Playwright allows you to programmatically decide where to save the file. You can move it from the temporary location to a permanent folder on your machine, giving you flexibility in managing test artifacts.

Assertions on Downloads:

Since the Download object provides information like the filename, path, and size, you can add assertions in your tests to confirm that the correct file was downloaded. This helps verify that the application is generating the expected content.


Why Important in Testing:

Handling downloads is critical in end-to-end testing because many applications allow users to export reports, invoices, or other data. Automating this ensures that not only is the UI interaction correct, but also the file itself is generated and downloadable as expected.












How It Works:

  • Trigger the download action on the page (example: clicking a button or link).
  • Wait for the Download event using page.waitForDownload().
  • Save the file locally using the download.saveAs() method.

<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.44.0</version> <!-- or latest -->
</dependency>


Java Code Example to Download File using Playwright


import com.microsoft.playwright.*;

import java.nio.file.Paths;

public class FileDownloadExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
             BrowserContext context = browser.newContext(
	                    new Browser.NewContextOptions().setAcceptDownloads(true)
	                );

            Page page = context.newPage();

            // Navigate to the page that has download link/button
            page.navigate("https://demo.automationtesting.in/FileDownload.html");

            // Click the first download link in the sample Word documents table
            Locator downloadLink = page.locator("a.btn:has-text('Download')");

            // Wait for the download to start and get the Download object
            Download download = page.waitForDownload(() -> {
                downloadLink.click(); // Trigger download
            });

            // Save the downloaded file to local path
            String downloadPath = "samplefile.pdf";
            download.saveAs(Paths.get(downloadPath));

            System.out.println("File downloaded to: " + downloadPath);

            browser.close();
        }
    }
}


Code explanation:

(a) While creating BrowserContext object, we have to do setAcceptDownloads(true)
(b)  Navigate to the page that has download link/button
(c) Click the first download link in the sample Word documents table
(d) Wait for the download to start and get the Download object
(e) Save the downloaded file to local path


Important Points:

  • waitForDownload() ensures Playwright listens for the download triggered by the action inside the callback.

  • You must call download.saveAs(Paths.get(...)) to save the file locally.

  • The file is stored in a temporary directory by default until saved manually.


Suggested Posts:

1. BrowserContext in Playwright
2. File Upload in Playwright
3. Comma Selectors in Playwright
4. Handle Dynamic Webtable in Playwright
5. Page Object Model in Playwright