I’m trying to upload a file using Playwright, but the input element is hidden:
<input type="file" class="xyz" accept=".jpg,.jpeg,.png,.doc,.docx,.xlsx,.xls,.csv,.pdf" hidden>
My current code:
await page.locator('//div/input[@class=xyz]').setInputFiles('Upload_files/CSV Test file.csv');
Does not work because the locator can’t find the hidden input. How can I send a file to an <input type="file" hidden> using Playwright?
I ran into this exact issue before. In Playwright, setInputFiles works even on hidden inputs, but you need to target the actual <input> element itself, not a wrapper <div>. For example:
// directly select the hidden input by class or attribute
const fileInput = page.locator('input.xyz[type="file"]');
await fileInput.setInputFiles('Upload_files/CSV Test file.csv');
Even though the input is hidden, Playwright allows setting files programmatically. You don’t need to make it visible or click anything.
I used to struggle with hidden file inputs too. One trick that works reliably is to avoid relative locators like a parent div and go straight to the input.
For example:
await page.locator('input[type="file"][class="xyz"]').setInputFiles('Upload_files/CSV Test file.csv');
Playwright ignores the hidden attribute for file uploads, so this will work without any hacks.
I tested this on several projects with hidden inputs, and it always worked.
From my experience, trying to click a hidden input never works.
Playwright has your back here: setInputFiles can send a file to a hidden input directly. Just make sure your selector points to the <input> itself, like:
const input = page.locator('input.xyz[type="file"]');
await input.setInputFiles('Upload_files/CSV Test file.csv');
I do this all the time in forms where the file input is styled via a label or button. No need to remove hidden or manipulate the DOM.