Upload files in Playwright, Upload file action in Playwright
Welcome to another episode of the Playwright with TypeScript series. In this video, we dive into how to upload single or multiple files using Playwright.
The video begins by explaining the manual process of uploading files via a web interface, where users click on a 'Choose Files' button, select the file(s) they want to upload, and click 'Open'. This action is then demonstrated programmatically using Playwright.
The key tool used in this demonstration is the locator.setInputFiles
method. To upload a single file, the method takes in the locator of the file input element and the complete file path as a string.
await page.locator('input[type="file"]').setInputFiles('path/to/file.txt');
For uploading multiple files, an array containing the paths of the files is passed to the same method.
await page.locator('input[type="file"]').setInputFiles(['path/to/file1.jpg', 'path/to/file2.png']);
The video showcases a practical example with two websites, deitw.name
and the-internet.herokuapp.com
, each having different file upload implementations. Using VS Code, a test script named practiceUploadFile.spec.ts
is pre-created, importing necessary modules from Playwright and using asynchronous functions to demonstrate both single and multiple file uploads.
For an element to support multiple file uploads, it must possess the multiple
attribute in its HTML tag.
<input type="file" multiple />
Additionally, the video explains handling cases where the HTML input element for a file upload isn't available. In such scenarios, listeners are used to simulate the file upload process. Particularly, the video demonstrates using page.waitForEvent('filechooser')
to handle file uploads triggered by non-input elements (like a div
), where the filechooser
event is awaited and processes the selected files programmatically.
const [fileChooser] = await Promise.all([
page.waitForEvent('filechooser'),
page.click('div#non-input-element'), // This triggers the file chooser
]);
await fileChooser.setFiles('path/to/file.txt');
Towards the end, the video covers removing uploaded files. By passing an empty array to the setInputFiles
method, it effectively clears the input field.
await page.locator('input[type="file"]').setInputFiles([]);
This comprehensive guide on file uploads using Playwright is a valuable tool for anyone looking to automate file operations within web applications. For a more in-depth understanding, code snippets, and further explanations, do watch the entire video.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].