How to upload file with JS/Puppeteer
Asked Answered
D

4

21

I'm trying to figure out how to upload a picture file into an input dialog. It isn't possible to just type in the name and hit enter as I don't see a way in order to automate that with Puppeteer. I figure I will have to set some value as the picture but I'm not sure how to do that. Any ideas?

Denitadenitrate answered 10/12, 2019 at 18:24 Comment(1)
While the issue is on Puppeteer, if you get the similar issue on Playwright you can refer to stackoverflow.com/questions/66132097Tifanytiff
H
35

You upload a file by using elementHandle.uploadFile.

Code Sample

const elementHandle = await page.$("input[type=file]");
await elementHandle.uploadFile('path/to/file');
await page.click('selector-of-submit-button');  // might not be necessary

Depending on whether the page directly react to the change of the element, you might need to click a button to submit the form.

Hobnail answered 10/12, 2019 at 18:38 Comment(0)
R
11

After few days of suffering that's works for me:

import path from 'path';

const filePath = path.relative(process.cwd(), __dirname + filepath);
await element.uploadFile(filePath);
await element.evaluate(upload => upload.dispatchEvent(new Event('change', { bubbles: true })));

based on this incredible answer from GitHub: https://github.com/puppeteer/puppeteer/issues/857#issuecomment-386222936

Ritchey answered 13/4, 2021 at 13:47 Comment(1)
Bro, you are my hero i spend two days on this and alltough through all information my own mixup and a lot of trial and error with ChatGPT finally your code brought it home... ! here is my section const filePath = 'C:\\Users\\maName\\Desktop\\backup\\THePage\\SomeMore\\inc.jpg'; const elementHandle = await page.$("input[type=file]"); await elementHandle.uploadFile(filePath); await elementHandle.evaluate(upload => upload.dispatchEvent(new Event('change', { bubbles: true })));Ecospecies
H
4

Here is the way you can use for yourself, but in typescript:

const uploadImage = async (
  imagePath: string,
  fileChooserTriggerXpath: string
) => {
  const p = getPage() // this return puppeteer page 
  const [fileChooser] = await Promise.all([
    p?.waitForFileChooser(),
    clickXpath(fileChooserTriggerXpath),
  ])

  await fileChooser?.accept([imagePath])
}
Hyperacidity answered 17/6, 2021 at 18:19 Comment(0)
M
0

I was very stuck and this helped: https://blog.apify.com/how-to-download-and-upload-files-in-puppeteer/#:~:text=Uploading%20files%20with%20Puppeteer,-To%20perform%20an&text=You%20can%20use%20the%20elementHandle,has%20a%20dialog%20while%20elementHadle.

//the code sample of FileChooser

const [fileChooser] = await Promise.all([
    page.waitForFileChooser(),
    page.click('#customUploadButton')
]);
await fileChooser.accept(['/path/file.jpg']);
Milanmilanese answered 21/6 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.