简体   繁体   中英

How do I upload a file with Puppeteer Sharp?

I'm using Puppeteer Sharp to test my web app. My web app has a button that triggers an <input type="file"> to let the user select a CSV file to upload.

How do I use that to upload a file when testing via Puppeteer Sharp? Just clicking the button isn't enough, because I need to give the browse-for-file dialog a path to the file.

You can use Page.WaitForFileChooserAsync to interact with the file chooser. The important thing to remember is you need to have the file chooser ready before you click the <input type="file"> .

For example:

var fileChooserDialogTask = page.WaitForFileChooserAsync(); // Do not await here

await Task.WhenAll(fileChooserDialogTask, page.ClickAsync("input[type='file']"));

var fileChooser = await fileChooserDialogTask;
await fileChooser.AcceptAsync(pathToFile);

If you try to click the <input type="file"> before you've called WaitForFileChooserAsync , you'll be stuck with the modal file chooser dialog waiting for you to do something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM