以选取图片为例
1.先获取当前窗口
const win = remote.getCurrentWindow()
2.获取选择的文件路径
调用remote.dialog.showOpenDialogSync方法,注意因为是在渲染进程内调用,所以用remote.dialog.showOpenDialogSync而不是直接用dialog.showOpenDialogSync
const paths: string[] | undefined = await remote.dialog.showOpenDialogSync(win, options)
3.将本地路径转化成File
const files: Array<File> = []
if (paths && paths.length > 0) {
// 本地文件的路径
paths.forEach((path: string) => {
const fileName = path.split('\\').pop() || ''
const buffer = readFileSync(path)
let file = new File([buffer], fileName)
files.push(file)
})
}
封装成方法,方便调用
import { remote } from 'electron'
import { readFileSync } from 'fs'
/**
* @description 选择图片
*/
async chooseFile(type: EMsgType): Promise<Array<File>> {
const options = {//只能选择图片类型文件,限制图片类型
filters: [{
name: 'Images',
extensions: ['jpg', 'png', 'gif', 'jpeg'],
},
],
properties: ['openFile', 'multiSelections'],
}
const win = remote.getCurrentWindow()
const paths: string[] | undefined =
await remote.dialog.showOpenDialogSync(win, options)
const files: Array<File> = []
if (paths && paths.length > 0) {// 本地文件的路径
paths.forEach((path: string) => {
const fileName = path.split('\\').pop() || ''
const buffer = readFileSync(path)
const file = new File([buffer], path)
files.push(file)
})
}
return files
}
Web前端(W3Cways.com) - Web前端学习之路