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?
How to upload file with JS/Puppeteer
Asked Answered
While the issue is on Puppeteer, if you get the similar issue on Playwright you can refer to stackoverflow.com/questions/66132097 –
Tifanytiff
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.
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
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
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])
}
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']);
© 2022 - 2024 — McMap. All rights reserved.