Friday, July 24, 2026

Playwright File Upload, Download & Drag-and-Drop Automation Using Java (Complete Guide)

Introduction

Modern web applications frequently require users to upload documents, download reports, or drag and drop files between different sections of the application.

Examples include:

  • Uploading profile pictures
  • Importing Excel spreadsheets
  • Downloading invoices or reports
  • Uploading resumes in job portals
  • Attaching files in support tickets
  • Dragging files into cloud storage applications

Automating these scenarios reliably is an essential skill for every automation engineer.

In this tutorial, you'll learn how to automate file uploads, file downloads, and drag-and-drop functionality using Playwright with Java.


Why File Handling Automation is Important

Many business-critical workflows depend on files.

Examples include:

  • Banking statement uploads
  • Insurance document verification
  • HR resume uploads
  • Medical report downloads
  • Invoice generation
  • Tax document processing

Automating these scenarios improves regression coverage and reduces manual effort.


Project Setup

Ensure your project includes the Playwright dependency.

<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.55.0</version>
</dependency>

Understanding File Upload in Playwright

Unlike Selenium, Playwright does not interact with the operating system's native file chooser.

Instead, it directly uploads files using the input element.

This makes uploads faster and more reliable.


Upload a Single File

Example:

page.navigate("https://example.com/upload");

page.setInputFiles(
    "input[type='file']",
    Paths.get("files/resume.pdf")
);

The selected file is uploaded immediately after it is assigned to the input element.


Upload Multiple Files

Some applications allow users to upload several files simultaneously.

page.setInputFiles(
    "input[type='file']",
    new Path[] {
        Paths.get("files/report.pdf"),
        Paths.get("files/image.png"),
        Paths.get("files/data.xlsx")
    }
);

Playwright uploads all selected files in one operation.


Remove Uploaded Files

To clear a previously selected file:

page.setInputFiles(
    "input[type='file']",
    new Path[] {}
);

This resets the file input field.


Handling Hidden File Inputs

Some applications hide the HTML file input and trigger it using a button.

Playwright can still upload files because it interacts directly with the input element.

Locate the hidden input and call:

page.setInputFiles(
    "#hiddenFileInput",
    Paths.get("files/document.pdf")
);

No JavaScript execution is required.


Working with File Chooser

Some websites open the file chooser after clicking a button.

Example:

FileChooser chooser =
    page.waitForFileChooser(() -> {

        page.click("#uploadButton");

    });

chooser.setFiles(
    Paths.get("files/profile.png")
);

Playwright waits for the chooser and then selects the file programmatically.


Downloading Files

Playwright provides built-in support for file downloads.

Example:

Download download =
    page.waitForDownload(() -> {

        page.click("#downloadReport");

    });

The Download object provides information about the downloaded file.


Save Downloaded File

Store the downloaded file in a specific directory.

download.saveAs(
    Paths.get(
        "downloads/report.pdf"
    )
);

This makes it easy to validate downloaded reports or archive test artifacts.


Verify Download

After saving the file, verify its existence.

Path path =
    Paths.get("downloads/report.pdf");

assert Files.exists(path);

You can also verify:

  • File name
  • File size
  • File extension
  • File content
  • Creation date

Drag and Drop

Many modern applications use drag-and-drop interactions.

Examples include:

  • Trello boards
  • Kanban applications
  • Cloud storage systems
  • Dashboard widgets

Playwright simplifies these actions.

page.dragAndDrop(
    "#source",
    "#target"
);

This performs the complete drag-and-drop interaction.


Drag Files into Upload Areas

Many websites support dragging files into a drop zone.

Typical flow:

  1. User selects a file.
  2. User drags it over the drop zone.
  3. Application uploads the file automatically.

In Playwright, this is usually implemented by uploading through the underlying file input element associated with the drop zone.


Validate Upload Success

Always verify that the upload completed successfully.

Example:

assertThat(
    page.locator(".success-message")
).containsText("Upload completed");

Validation is more reliable than assuming the upload succeeded.


Organizing Test Files

Store reusable files in a dedicated directory.

Example:

src

└── test

    └── resources

        └── testdata

            ├── sample.pdf

            ├── image.png

            ├── resume.docx

            └── report.xlsx

This structure keeps your project clean and portable.


Common Upload Challenges

File Size Restrictions

Applications may reject files larger than the allowed limit.

Test:

  • Small files
  • Large files
  • Boundary values

Unsupported File Types

Validate that unsupported formats produce appropriate validation messages.

Example:

  • Upload .exe
  • Upload .zip
  • Upload .bat

Verify that the application blocks invalid uploads.


Duplicate Uploads

Ensure the application correctly handles repeated uploads of the same file.


Interrupted Uploads

Test behavior during:

  • Network interruptions
  • Session expiration
  • Browser refresh
  • Upload cancellation

Best Practices

Store Test Files in Version Control

Keep sample files inside the project so that all team members use the same test data.


Use Relative Paths

Avoid absolute paths such as:

C:\Users\John\Desktop\file.pdf

Instead, use project-relative paths to improve portability.


Verify Download Content

Checking only the file name is insufficient.

Validate:

  • Content
  • Size
  • Format
  • Generated values

Keep Test Files Small

Large files increase execution time and repository size.

Use compact sample files unless testing file size limits.


Clean Up Download Directories

Delete temporary files after execution to prevent unnecessary storage growth.


Common Interview Questions

How does Playwright upload files?

Playwright uploads files by assigning them directly to the HTML file input element using setInputFiles(), without interacting with the native operating system file picker.


Can Playwright upload multiple files?

Yes. Pass an array of Path objects to setInputFiles().


How do you verify a downloaded file?

Save the file using download.saveAs() and validate its existence, size, name, or contents.


Does Playwright support drag-and-drop?

Yes. The dragAndDrop() method performs drag-and-drop interactions between source and target elements.


Why use relative file paths?

Relative paths make the framework portable across different operating systems, developers' machines, and CI/CD environments.


Conclusion

File handling is a critical aspect of end-to-end web automation.

Playwright provides simple and reliable APIs for uploading files, downloading reports, handling file chooser dialogs, and automating drag-and-drop interactions.

In this guide, you learned how to:

  • Upload single and multiple files
  • Handle hidden file inputs
  • Work with the file chooser
  • Download and verify files
  • Perform drag-and-drop actions
  • Organize test resources
  • Apply enterprise best practices

By mastering these techniques, you'll be able to automate many real-world business workflows involving documents, reports, and media files with confidence.

No comments:

Post a Comment