How do I handle file uploads with Puppeteer?
Rashid D
rashid d profile pic

Handling file uploads with Puppeteer involves interacting with file input elements and providing the file path or data to be uploaded. Here is a detailed explanation of the process: 1. Locating the file input element: Find the file input element on the page using CSS selectors or other appropriate methods. For example:

1
2
3

   const fileInput = await page.$('input[type="file"]');
   

2. Uploading a file using thefileInput.uploadFile() method: Use theuploadFile() method to upload a file to the file input element. The method accepts the file path or an array of file paths to be uploaded. Make sure to provide the full path to the file.

1
2
3
4

   const filePath = '/path/to/file.txt';
   await fileInput.uploadFile(filePath);
   

3. Handling cases where file input is hidden or not directly interactable: In some cases, the file input element may be hidden or not directly interactable. In such situations, you can work around this limitation by injecting JavaScript code to trigger a click event on the element.

1
2
3
4
5
6
7

   await page.evaluate((fileInput) => {
     fileInput.style.display = 'block'; // Make the file input element visible if necessary
     fileInput.click(); // Trigger a click event on the file input element
   }, fileInput);
   await fileInput.uploadFile(filePath); // Upload the file after triggering the click event
   

4. Uploading multiple files: If the file input element supports multiple file uploads (), you can provide an array of file paths to theuploadFile() method to upload multiple files.

1
2
3
4

   const filePaths = ['/path/to/file1.txt', '/path/to/file2.txt'];
   await fileInput.uploadFile(filePaths);
   

5. Uploading files from memory or streams: Puppeteer also supports uploading files from memory or streams using thepage.evaluateHandle() method. You can create aBlob object in the browser context and pass it to the file input element.

1
2
3
4
5
6
7
8
9

   const blob = await page.evaluateHandle((content, fileName) => {
     const blob = new Blob([content], { type: 'application/octet-stream' });
     return URL.createObjectURL(blob);
   }, 'File content', 'file.txt');

   await fileInput.uploadFile(blob.asElement()); // Upload the file from the Blob
   await page.evaluate((blobURL) => URL.revokeObjectURL(blobURL), blob.toString()); // Clean up the Blob URL
   

6. Verifying the successful upload: After the file upload, you can check if the upload was successful by performing additional assertions or interacting with other elements on the page. By following these steps, you can handle file uploads with Puppeteer. You can locate the file input element, provide the file path or data, and trigger the upload. Additionally, you can handle scenarios where the file input element is hidden or not directly interactable, and upload multiple files or files from memory.