使用puppeteer完成监听浏览器下载文件并保存到自己本地或服务器上完成上传功能
创始人
2025-01-17 04:02:46
0

需求场景

获取网站点击的下载pdf,并把pdf重命名再上传到COS云上面

技术使用

“puppeteer”: “^19.7.2”,
“egg”: “^3.15.0”, // 服务期用egg搭的
文件服务使用COS腾讯云

核心思路

获取浏览器下载事件,并把文件保存到本地

const session = await substitutePage.target()       .createCDPSession();     await session.send('Page.setDownloadBehavior', {       behavior: 'allow',       downloadPath, // 指定文件保存路径回家     }); 

在保存到本地前监听此文件夹,如果有文件则获取并上传
加timer做防抖是为了防止在文件写入时以及重命名文件时多次触发watch函数,导致出会出现0KB源文件脏数据

 let timer: any = null;  fs.watch(downloadPath, async (_eventType, filename) => {  if (timer !== null) {  clearTimeout(timer);    }    timer = setTimeout(() => {      // 防止出现下载的临时文件就触发      if (filename.endsWith('.pdf')) {        resolve({          filename,        });      }    }, 500);  }); 

完整代码

    const session = await substitutePage.target()       .createCDPSession();     await session.send('Page.setDownloadBehavior', {       behavior: 'allow',       downloadPath, // 指定文件保存路径回家     });      // res就是文件相关信息了     const [ res ] = await this.downloadPdfHandler(substitutePage, downloadPath);     // filePath就是自己本地的文件所在绝对路径     const filePath = `${downloadPath}/${res.fileName}`;     // uploadFile是cos文件上传相关实现, 我就不放了,有私密的key     const pdfUriCode = await this.uploadFile(filePath, filePath);     const pdfUri = decodeURIComponent(pdfUriCode);     this.domainList = {       pdfSize: res.pdfSize,       pdfUri: pdfUri.substring(pdfUri.indexOf('root')),     }; 

downloadPdfHandler函数实现

  downloadPdfHandler(page, downloadPath): Promise {     const uuidName = uuidv4();     const fsWatchApi = () => {       // 使用防抖是为了防止下载的文件没有写入完全就重命名,那样会产生一个脏文件       let timer: any = null;       return new Promise<{ filename: string }>(resolve => {         fs.watch(downloadPath, async (_eventType, filename) => {           if (timer !== null) {             clearTimeout(timer);           }           timer = setTimeout(() => {             // 防止出现下载的临时文件就触发             if (filename.endsWith('.pdf')) {               resolve({                 filename,               });             }           }, 500);         });       });     };      function responseWatchApi() {       return new Promise(resolve => {         page.on('response', async response => {           // 检查响应是否为application/octet-stream且可能包含PDF(或你期望的其他文件类型)           if (response.headers()['content-type'].startsWith('application/octet-stream')) {             resolve();           }         });       });     }      return new Promise(async (resolve, reject) => {       try {          const [ , { filename }] = await Promise.all([ responseWatchApi(), fsWatchApi() ]);         const oldFilePath = path.join(downloadPath, filename);         const newFilePath = path.join(downloadPath, `${uuidName}.pdf`);         try {           fs.renameSync(oldFilePath, newFilePath);           this.logger.info(`文件名已经被修改完成:${uuidName}`);         } catch (error) {           this.logger.info(`文件名已经被修改完成:${uuidName}`);         }         await this.sleep(5 * 1000);         const files = fs.readdirSync(downloadPath);         // 创建一个数组,将文件名和其mtime(最后修改时间)一起存储         const filesWithMtime = files.map(file => {           const filePath = path.join(downloadPath, file);           const stats = fs.statSync(filePath);           return { fileName: file, mtime: stats.mtime, size: stats.size };         });         const newestFile = filesWithMtime.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0];         this.logger.info('newestFile: %o', {           newestFile,         });         resolve({           pdfSize: newestFile.size,           fileName: newestFile.fileName,         });        } catch (e) {         reject(e);       }     });   } 

相关内容

热门资讯

技术分享!多乐辅助下载,南丰数... 技术分享!多乐辅助下载,南丰数刀脚本-原来真的是有辅助教程(有挂细节)小薇(辅助器软件下载)致您一封...
记者揭秘!微信边锋辅助挂件,战... 记者揭秘!微信边锋辅助挂件,战皇大厅辅助那个可靠-果然真的有辅助教程(确实有挂)1、实时微信边锋辅助...
重大通报!哈局八张模拟器,新广... 重大通报!哈局八张模拟器,新广西老友辅助-切实有辅助教程(真实有挂)1、让任何用户在无需哈局八张模拟...
揭秘攻略!茶馆游戏辅助,填大坑... 揭秘攻略!茶馆游戏辅助,填大坑辅助器视频-都是是有辅助app(有挂细节)1、首先打开填大坑辅助器视频...
详细说明!雀友会广东潮汕麻雀,... 详细说明!雀友会广东潮汕麻雀,四川徒有辅助软件-原来是真的有辅助神器(详细教程)1、进入到雀友会广东...
记者揭秘!吉安中至小程序,微乐... 记者揭秘!吉安中至小程序,微乐陕西小程序破解器-切实是有辅助教程(有挂教程)1、许多玩家不知道微乐陕...
玩家攻略!吉祥填大坑小程序辅助... 玩家攻略!吉祥填大坑小程序辅助,心悦填大坑辅助-果然真的有辅助教程(有挂助手)1、全新机制【吉祥填大...
盘点一款!河南微乐麻将小程序辅... 盘点一款!河南微乐麻将小程序辅助器,友友联盟有辅助吗-确实是有辅助攻略(真的有挂)1、河南微乐麻将小...
信息共享!手机游戏辅助脚本工具... 信息共享!手机游戏辅助脚本工具,西兵互娱辅助插件app-一贯真的是有辅助教程(有挂解惑)一、手机游戏...
关于!欢乐情怀怎么开挂,指尖四... 关于!欢乐情怀怎么开挂,指尖四川辅助脚本视频-其实存在有辅助工具(有挂方法)1、欢乐情怀怎么开挂透视...