Welcome folks today in this blog post we will be using the puppeteer
library to upload files and images
to express server using filechooser
. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project using the below command
npm init -y
npm i puppeteer
And after that you need to make an index.js
file and copy paste the following code
To upload files or images using Node.js and Puppeteer, you can use the page.selectFile()
method to simulate a file selection dialog and select the desired file. Then you can use the page.uploadFile()
method to upload the selected file to the server.
Here’s an example of how you might use these methods to upload a file to an Express server:
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
const puppeteer = require('puppeteer'); const express = require('express'); const app = express(); app.use(express.static('public')); app.use(express.json()); app.post('/upload', (req, res) => { // Handle file upload }); app.listen(3000, () => { console.log('Server listening on port 3000'); }); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('http://localhost:3000'); // Select file const fileChooser = await page.waitFor('input[type="file"]'); await fileChooser.uploadFile('/path/to/file'); // Submit form await page.evaluate(() => { document.querySelector('form').submit(); }); // Wait for server response await page.waitForNavigation(); console.log(await page.content()); await browser.close(); })(); |
Once you have the endpoint, you can use the fetch()
function or any other http library like axios
to send the file to the server.