简体   繁体   中英

Chrome download error when downloading file with Puppeteer

I have an application that shows a page, the user clicks on a button, and downloads a CSV file. I want to run this with Puppeteer.

Problem is that the CSV is downloaded empty and with an error. This happens both with headless true and false. The page finished loading, and I increased the timeout, but it still fails. What could be the issue?

在此处输入图像描述

const puppeteer = require('puppeteer');

(async () => {
    
    const browser = await puppeteer.launch({
       headless: false
    });

    const page = await browser.newPage();
    await page.goto('http://localhost:4400/login', { waitUntil: 'networkidle2' });    
    
    await page._client.send('Page.setDownloadBehavior', {
        behavior: 'allow',
        downloadPath: './',
    });

    await page.waitForSelector('#run-and-export');
    await page.click('#run-and-export');
  
    // file-downloaded is turned on when the file finished downloading (not to close the window)
    await page.waitForSelector('#file-downloaded', { timeout: 120000 }); 

    await browser.close();
    
})();

The code in the application that generates the file to download is an Angular service:

@Injectable({ 
    providedIn: 'root' 
})
export class DownloadService {

    downloadFile(content:any, fileName: string, mimeType: string){
    
        var blob = new Blob([(content)], {type: mimeType});
        var a = document.createElement('a');
        a.href = window.URL.createObjectURL(blob);
        a.download = fileName;
        a.click();

    }
}

This is what made this work:

const downloadPath = path.resolve('/my/path');

await page._client.send('Page.setDownloadBehavior', {
    behavior: 'allow',
    downloadPath: downloadPath 
});

I got the same problem, the download failed, in the download dir I got filename.pdf.crdownload and no other file.

The download dir is up two levels from the app dir ../../download_dir

The solution was (as suggested by ps0604):

const path = require('path');
const download_path = path.resolve('../../download_dir/');

await page._client.send('Page.setDownloadBehavior', {
    behavior: 'allow',
    userDataDir: './',
    downloadPath: download_path,
});

If someone is searching for .crdownload file and download error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM