How to upload BUFFER of image to any website with puppeteer?

Viewed 239

Here's what I know how to do:

  • Download an image from somewhere like imgur, capture it as a buffer, save to disk
  • Write an image from disk to a page using elementHandle.uploadFile(path)

However, this solution only works on my local machine. I'm looking to run puppeteer in the cloud, which means that I won't have access to a static disk with file paths. What I'm trying to do, therefore, is omit the disk as a middleman. Once I have the image as a buffer, I want to just directly upload that buffer into the input. I figured that the source code for elementHandle.uploadFile(path) would be a good place to start, as I'm pretty much just looking to peel back a layer of abstraction. However, I can't find it in puppeteer's github

1 Answers
const downloadImgFromUrl = async (url, dest) => {
    // Create an empty file where we can save data
    const file = fs.createWriteStream(dest);

    // Using Promises so that we can use the ASYNC AWAIT syntax
    await new Promise((resolve, reject) => {
        request({
            uri: url,
            gzip: true,
        }).pipe(file).on('finish', async () => {
            console.log(`Image downloaded from Storage`);
            resolve();
        }).on('error', (error) => {
            reject(error);
        });
    }).catch((error) => {
        console.log(`Image download from URL failed: ${error}`);
    });
}

    await page.waitForTimeout(1000)
    const [filechooser] = await Promise.all([
      page.waitForFileChooser(),
      page.focus("#attach_file_photo"),
      page.click('#attach_file_photo')
    ])

    await downloadImgFromUrl(imgUrl, path.join(os.tmpdir(),'uploadimg.png'))

    await filechooser.accept([path.join(os.tmpdir(), 'uploadimg.png')])
Related