Electron下载插件 or 固件至本地

最近有个特殊需求,由于路由器PCB板子是办公类型,无线传输类型,在特定情况下没有网络支持。则桌面应用程序里面的远程升级路由器功能无法使用,则就需要将OTA升级降至本地通过局域网的HTTP请求去实现。

1.下载代码

        Downloads(url){
                var that = this;
                var http = require('http');
                var fs = window.require('fs');
                http.get(url, (res) => { 
					var localFirmwareUrl = process.env.NODE_ENV == "development"? __dirname.split("node_modules")[0]+"build/NewFirmware":__dirname.split("Tools")[0]+"Services/Services";
					if (res.statusCode !== "200") {
						const file = fs.createWriteStream(localFirmwareUrl)
						// 进度
						const len = parseInt(res.headers['content-length']);// 文件总长度
						let cur = 0;
						res.on('data', function (chunk) {
							cur += chunk.length;
							const progress = (100.0 * cur / len).toFixed(2);// 当前进度
							const currProgress = (cur / 1048576).toFixed(2);// 当前了多少
							// console.log(progress);
							// console.log(currProgress + "M");
							that.Download.len = progress/5;
							document.getElementById("restart_step").style.cssText += "width: " + progress/5 + "%;";
						})
						//下载结束
						res.on('end', () => {
							
						})
						//文件写入结束
						file.on('finish', () => {
							file.close();
                            that.File_Upload();
						}).on('error', (err) => {
							fs.unlink(localFirmwareUrl,(e)=>{console.log(e)});
							if (err) {
								console.log(err);
							}
						})
						res.pipe(file);
					} else {
						console.log("网络环境错误!");
						ipcRenderer.sendSync('message', JSON.stringify({
							command: "notification",
							title: that.$t("notification.title_2"),
							body: that.$t("notification.body_27")
						}));
					}
			    })
            },

2.将文件封装成formData

BufConvertFile(url, filename) {
	var fs = window.require('fs');
	console.log(url)
	return new Promise((resolv, reject) => {
		fs.readFile(url, (err, data) => {
			if (err) {
				return
			}
			const blob = new Blob([data], { type: 'text/plain' });
			const file = new File([blob], filename, { type: 'text/plain' });
			resolv(file);
		})
	})
}


File_Upload(){
    var { BufConvertFile } = require('../../utils/util');
	var url = process.env.NODE_ENV == "development"? __dirname.split("node_modules")[0]+"build/NewFirmware":__dirname.split("Tools")[0]+"Services/NewFirmware";
    BufConvertFile(url, "NewFirmware").then(res=>{
    var formData = new FormData();
    formData.append('file', res);
    this.$axios_post(this.$store.state.content.device_service_ip + this.$axios_url_upload + "?req=" + this.$encrypt("sid=" + this.$store.state.content.session_id), formData).then(res=>{
        if(res.status==200){
			this.Resume();
        }else{
			ipcRenderer.sendSync('message', JSON.stringify({
				command: "notification",
				title: that.$t("notification.title_2"),
				body: that.$t("notification.body_26")
				}));
			}
      })
   })
 },

3.下载进度条

//HTML
<div id="restart_step" style="position: relative; top: -10px; width: 0%; height: 10px; background: #226FE3; border-radius: 6px;"></div>

Resume(){
    this.Download.len == 20;
    var stop = setInterval(() => {
       if (this.Download.len >= 100) {
            clearInterval(stop);
            this.$emit("closed_ota", false);
            this.reconnect(this.action_info.ssid,this.action_info.title);
        } else {
            this.Download.len += 2;
             document.getElementById("restart_step").style.cssText += "width: " + this.Download.len + "%;";
        }
   }, 1000);
},

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Electron 的 `desktopCapturer` API 来进行截图。这个 API 允许你从用户的显示器中捕获屏幕、窗口或标签页的内容。以下是一个简单的例子: ```javascript const { desktopCapturer } = require('electron') desktopCapturer.getSources({ types: ['window', 'screen'] }).then(async sources => { for (const source of sources) { if (source.name === 'Entire Screen' || source.name === 'Screen 1') { try { const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: source.id, minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }) handleStream(stream) } catch (e) { handleError(e) } return } } }) function handleStream (stream) { const video = document.createElement('video') video.srcObject = stream video.onloadedmetadata = () => { video.play() const canvas = document.createElement('canvas') canvas.width = video.videoWidth canvas.height = video.videoHeight const ctx = canvas.getContext('2d') ctx.drawImage(video, 0, 0, canvas.width, canvas.height) const imgUrl = canvas.toDataURL() // 在这里可以上传 imgUrl 到服务器或者进行其他操作 } } function handleError (e) { console.log(e) } ``` 这个例子中,我们首先使用 `desktopCapturer.getSources` 来获取可以捕获的源,然后选择一个源来获取媒体流,最后使用 `canvas` 来抓取视频帧并将其转换为图片数据。你可以使用这个图片数据来上传到服务器或者进行其他操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值