Search code examples
javascriptnode.jsautomationpuppeteerfs

With Puppeteer How To Upload Random Files From A Directory and Delete It?


I want to write a puppeteer script with node js to upload a random file from a directory to the server and delete it.

Here is the HTML code in the site:

<form action="/server.php">
  <input type="file" id="myFile" name="filename">
  <input type="submit">
</form>

So now I need to upload an image file from a directory (but I don't know the image name) and after that, I need to delete that file from the directory.

Here is my current puppeteer code:

//UPLOAD A PICTURE
const fileName = 'dont-know-the-name.png';
const picInput = await page.$('#myFile');
await picInput.uploadFile(fileName);

Solution

  • Actually, what takes care of uploading a file is Puppeteer's ElementHandle.uploadFile() method.. You would want to use Node's fs.readDir() to get an array of the file in the dir, take a random element and then use fs.unlink() to delete it.

    Here's an implementation:

    const dir = "YOUR/DIR/PATH";
    const rnd = (arr) => arr[Math.floor(Math.random() * arr.length)];
    const rndFile = () => `${dir}/${rnd(fs.readdirSync(dir))}`;
    
    (async () => {
        const browser = await puppeteer.launch({headless: false});
        const page = await browser.newPage();
        await page.goto("YOUR/UPLOAD/URL")
        
      const file = rndFile();
      const elementHandle = await page.$("input[type=file]");
      await elementHandle.uploadFile(file);
      await page.click("input[type=submit]")
      
      fs.unlinkSync(file)
    })();