1.点击文件按钮图标,判断上传文件类型:图片、视频、文件

// 发送文件入口async sendFile() {const imageType = ['jpg', 'png', 'jpeg']const videoType = ['mkv', 'avi', 'mp4']const options = {filters: [{ name: 'Images', extensions: imageType },{ name: 'Videos', extensions: videoType },{ name: 'Files', extensions: ['zip', 'rar'] }]}const result = await dialog.showOpenDialog(options)if (!result.canceled && result.filePaths) {const filePaths = result.filePaths[0]const isImage = imageType.some((e) => filePaths.endsWith(e))const isVideo = videoType.some((e) => filePaths.endsWith(e))if (isImage) {this.sendImage(result)} else {this.sendVideo(result, isVideo)}}}

2.通过COS 上传demo

async sendFile(result, isVideo) {const filePaths = result.filePaths[0]const pathArr = filePaths.split(/\\/)const fileName = pathArr[pathArr.length - 1]const path = filePaths.replace(/\\/g, '/')const file = await this.srcToFile(path, fileName)const fileContentType = /\.zip$/.test(fileName)? 'application/x-zip-compressed': 'application/x-rar-compressed'let keyPath = `${common.isUat() ? 'pathUat' : 'pathProd'}`let data_taskId = ''this.cos.uploadFile({Bucket,Region,Key: keyPath + fileName,ContentType: isVideo ? 'video/mp4' : fileContentType,Body: file,SliceSize: 1024 * 1024 * 5,onTaskReady: (taskId) => {data_taskId = `[data-taskId=${taskId}]`if (isVideo) {const fs = require('fs')const videoData = fs.readFileSync(path)const url = `data:video/mp4;base64,${videoData.toString('base64')}` // 获取本地视频的地址在页面显示let audioElement = new Audio(URL.createObjectURL(file))audioElement.addEventListener('loadedmetadata', (_event) => {let duration = common.formatDuraton(Math.floor(audioElement.duration)) // 获取视频时长console.log(duration);})}},onProgress: (info) => {console.log('onProgress', JSON.stringify(info))var percent = Math.floor(info.percent * 10000) / 100var speed = Math.floor((info.speed / 1024 / 1024) * 100) / 100console.log('进度:' + percent + '%; 速度:' + speed + 'Mb/s;')}},(err, data) => {if (err) {console.log('上传出错', err)} else {console.log('上传成功', data)}})}

3.根据本地路径创建文件对象

// 根据本地路径创建文件对象srcToFile(src, fileName, mimeType) {return fetch(src).then(function (res) {return res.arrayBuffer()}).then(function (buf) {return new File([buf], fileName)})}