我目前正在使用node.js和电子在Javascript和Jquery中创建一个应用程序,该应用程序将在第一次运行时下载它的db文件。我希望实现progressbar.js,以便在文件下载时显示下载栏。我遵循progressbar.js的安装指南,实现了ourcodeworld.com的javascript下载,但是在运行我的电子应用程序时,下载栏根本不呈现。我如何使它以电子方式工作,以便进度条呈现并显示下载进度?
HTML代码
<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");
发布于 2017-10-15 22:24:29
您总是用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
}
用于在没有动画的情况下精确设置值。
https://stackoverflow.com/questions/46763893
复制