[英]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.我有一个显示页面的应用程序,用户单击一个按钮,然后下载 CSV 文件。 I want to run this with Puppeteer.
我想用 Puppeteer 运行它。
Problem is that the CSV is downloaded empty and with an error.问题是 CSV 下载为空并出现错误。 This happens both with
headless
true and false. headless
真假都会发生这种情况。 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:应用程序中生成要下载的文件的代码是一个 Angular 服务:
@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.我遇到了同样的问题,下载失败,在下载目录中我得到了
filename.pdf.crdownload
而没有其他文件。
The download dir is up two levels from the app dir ../../download_dir
下载目录比应用程序目录
../../download_dir
The solution was (as suggested by ps0604):解决方案是(如 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.如果有人在搜索
.crdownload
文件并下载错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.