electron-vue-admin下载网络文件,保存并显示下载进度

1、安装

npm install request

2、完整代码

var request = require('request');
var fs = require('fs');

/**
 * 处理开始下载文件
 */
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.
		console.log("data.headers['content-length']",data)
		total_bytes = parseInt(data.headers['content-length']);
	});
	req.on('data', function(chunk) {
		// Update the received bytes
		received_bytes += chunk.length;
		showProgress(received_bytes, total_bytes);
	});
	req.on('end', function() {
		alert("File succesfully downloaded");
	});
}
/**
 * 处理显示进度
 */
function showProgress(received, total){
    var percentage = (received * 100) / total;
    console.log(percentage + "% | " + received + " bytes out of " + total + " bytes.");
}
/**
 * 下载示例
 */
downloadFile("https://fanyi-cdn.cdn.bcebos.com/static/translation/img/header/logo_e835568.png", "C:\\Users\\download\\Downloads\\logo_e835568.png");

你可能感兴趣的:(vue.js,electron,网络)