File Upload in Playwright

 

In Playwright Java, uploading a file is done using the setInputFiles() method. This method is used with an <input type="file"> element to simulate file uploads, just like a user would select a file using a file chooser dialog.




Steps to Upload a File in Playwright (Java)

  • Locate the file input element on the page using a suitable locator.
  • Use setInputFiles(Path file) or setInputFiles(FilePayload file) to simulate uploading the file.
  • Optionally, click the submit button if needed.


Example Scenario

Let's assume we have an HTML element like:

<input type="file" id="uploadFile">




Java Code Example


import com.microsoft.playwright.*;
import java.nio.file.Paths;

public class FileUploadExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            Page page = browser.newPage();

            // Go to a page with file upload field
            page.navigate("https://the-internet.herokuapp.com/upload");

            // Locate the input element and upload file
            page.locator("input#file-upload").setInputFiles(Paths.get("example.txt"));

            // Click the Upload button
            page.locator("input#file-submit").click();

            // Optional: verify upload success message
            String uploadedMessage = page.locator("h3").textContent();
            System.out.println("Upload Result: " + uploadedMessage);
        }
    }
}




Maven Dependency 


<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.43.0</version> <!-- Use latest version -->
</dependency>



No comments:

Post a Comment