我目前正在使用node.js和电子在Javascript和Jquery中创建一个应用程序,它将在首次运行时下载它的db文件。我想实现progressbar.js,以便在下载文件时显示下载栏。我正在按照progressbar.js的设置指南进行操作,并从ourcodeworld.com开始实施javascript下载,但是,在运行我的电子应用时,下载栏根本无法呈现。如何让它在电子中工作,以便进度条呈现并显示下载进度?
HTML CODE
<body>
<div id="container"></div>
</body>
使用Javascript / Jquery的
var bar = new ProgressBar.Line(container, {
strokeWidth: 4,
easing: 'easeInOut',
duration: 1400,
color: '#FFEA82',
trailColor: '#eee',
trailWidth: 1,
svgStyle: { width: '100%', height: '100%' }
});
function progress() {
bar.animate(1.0); // Number from 0.0 to 1.0
}
function downloadFile(file_url, targetPath) {
// Save variable to know progress
var received_bytes = 0;
var total_bytes = 0;
var req = request({
method: 'GET',
uri: file_url
});
var out = fs.createWriteStream(targetPath);
req.pipe(out);
req.on('response', function (data) {
// Change the total bytes value to get progress later.
total_bytes = parseInt(data.headers['content-length']);
});
req.on('data', function (chunk) {
// Update the received bytes
received_bytes += chunk.length;
progress();
});
req.on('end', function () {
alert("File succesfully downloaded");
});
}
downloadFile("http://www.planwallpaper.com/static/images/butterfly-wallpaper.jpeg", "./varbutterfly-wallpaper.jpeg");
答案 0 :(得分:2)
您总是使用1.0
为进度赋值function progress() {
bar.animate(1.0); // Number from 0.0 to 1.0
}
所以请把它改成
function progress(val) {
bar.animate(val); // Number from 0.0 to 1.0
}
然后从
更改更新req.on('data', function (chunk) {
// Update the received bytes
received_bytes += chunk.length;
progress();
});
到这个
req.on('data', function (chunk) {
// Update the received bytes
received_bytes += chunk.length;
progress(received_bytes/total_bytes);
});
正如您所看到的,您将发现每个块更新的进度更改并将其除以total_bytes
如果全部已下载,那么它将是1.0,否则将是您需要的动画。
或者您可以将进度功能更改为
function progress(val) {
bar.set(val); // Number from 0.0 to 1.0
}
用于在没有动画的情况下完全设置值。