Dockerfile
FROM ghcr.io/puppeteer/puppeteer:latest
RUN npm install express ali-oss
COPY app.js .
CMD node app.js
app.js
const express = require('express');
const puppeteer = require('puppeteer');
const OSS = require('ali-oss');
const app = express();
const port = 3000;
app.use(express.json());
// Replace with your own OSS configuration
const ossConfig = {
accessKeyId: 'xxxx',
accessKeySecret: 'xxxx',
bucket: 'zzzzz',
region: 'oss-cn-hangzhou'
};
const ossClient = new OSS(ossConfig);
app.get('/screenshot', async (req, res) => {
const { url } = req.query;
if (!url) {
return res.status(400).json({ error: 'Missing "url" parameter.' });
}
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
const screenshot = await page.screenshot();
await browser.close();
// Generate a unique filename for the screenshot
const filename = `screenshot-${Date.now()}.png`;
console.log(filename)
// Upload the screenshot to OSS
const result = await ossClient.put(filename, screenshot);
// Construct the OSS URL for the uploaded image
const imageUrl = result.url;
res.json({ imageUrl });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'An error occurred while taking the screenshot and uploading it to OSS.' });
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});