vue+electron中实现文件下载打开wps预览

下载事件

win.webContents.downloadURL(url)

触发session的will-download事件

javascript 复制代码
win.webContents.session.on('will-download', (event, downloadItem, webContents) => {
	// 设置文件保存路径
    // 如果用户没有设置保存路径,Electron将使用默认方式来确定保存路径(通常会提示保存对话框)
    item.setSavePath(savePath)
	
	item.on('updated', (event, state) => {
	// 监听下载过程, state有两种情况
	// interrupted 下载被中断,可恢复
	// progressing 下载进行中,可获取下载进度
     	if (state === 'interrupted') {
      	 // 可恢复下载
      	} else if (state === 'progressing') {
	        if (downloadItem.isPaused()) {
	        	console.log('Download is paused')
	        } else {
	        // 可以根据字节大小设置进度条
        	console.log(`Total bytes: ${downloadItem.getTotalBytes()}`)      
        	console.log(`Received bytes: ${downloadItem.getReceivedBytes()}`)
        	}
      	}
   	})
	
	item.once('done', (event, state) => {
	// 下载结束
      if (state === 'completed') {
      	// 下载成功
        console.log('Download successfully')
        // 用应用程序打开文件
        openFile(downloadItem.getSavePath())
      } else {
      	// state为cancelled或interrupted
      	// 下载取消或下载已经中断,无法恢复
        console.log(`Download failed: ${state}`)
      }
      // 这里可将下载结束的状态传回给渲染进程
      win.webContents.send('downstate', state)
    })
})

shell 使用默认应用程序管理文件和 url,提供与桌面集成相关的功能

shell.openPath(path) 以桌面的默认方式打开给定的文件。

javascript 复制代码
function openFile(filePath) {
	const path = require('path');
  	shell.openPath(path.join(filePath));
}
相关推荐
GISer_Jing4 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩4 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车4 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
丷丩8 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
xiaohua0708day9 小时前
Lodash库
前端·javascript·vue.js
万物皆对象6669 小时前
切换路由时页面空白问题(vue3)
前端·vue.js·typescript
突然好热9 小时前
TS 调试技巧
前端·javascript·typescript
h64648564h9 小时前
Flutter 国际化(i18n)全指南:一键切换中/英/日多语言
前端·javascript·flutter
丷丩11 小时前
MapLibre GL JS第8课:禁用滚动缩放
javascript·mapbox·maplibre gl js
李剑一11 小时前
小红书前端架构面试问的挺深入啊!面试官:Vue中组合式API与选项式API的设计权衡
vue.js·面试