簡體   English   中英

Puppeteer 中止文件下載到磁盤 - 如何實現它?

[英]Puppeteer abort file download to disk - how to implement it?

祝大家有美好的一天。 我有一個非常簡單的代碼,可以將文件下載到硬盤上。 它完美無缺。 轉到該站點,單擊文件鏈接到的鏈接,然后 baruser 將此文件保存到默認路徑。 但有時我需要在文件上傳開始后取消文件上傳。 我該怎么做呢?

例子

 const puppeteer = require('puppeteer-extra') async function main() { let browser = await puppeteer.launch({ headless: false, args: [ '--window-size=1200,1400', '--window-position=000,000', '--no-sandbox', '--disable-dev-shm-usage', '--disable-web-security', '--disable-features=IsolateOrigins', '--disable-site-isolation-trials' ] }) let page = await browser.newPage(); await page.goto('http://example.com/'); await page.waitForSelector('#download'); await page.hover('#download'); await page.click('#download'); // After clicking on the link, the file download begins } main().catch((e) => { throw e })
 <a href="/files.zip" id="download">download files</a>

  • nodejs v12.22.9
  • Chromium 版本 101.0.4950.0(開發人員構建)(64 位)
  • 木偶師^13.7.0
  • 木偶師-額外 ^3.2.3

您可以獲取文件路徑並使用流獲取文件,而不是單擊鏈接。

const https = require('https');

let stream
function abortStream() {
  if (stream) {
    stream.abort();
  }
}

// ... your code


const filePath = await page.$eval('#download', file => file.href);
const url = 'https://somesite.com'
https.get(`${url}${filePath}`, res => {
  stream = fs.createWriteStream('file.zip');
  res.pipe(stream);
  stream.on('error', ()=>{
     stream = undefined;
  })
  stream.on('finish', () => {
     stream.close();
     stream = undefined;
  })
})

調用abortStream()以中止文件下載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM