electron打开选择文件窗口,选中后返回file类型

2021-11-16阅读(2662)评论(0)牵着狗狗看MM

苏州实时公交查询

以选取图片为例

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
}

 

赞(2)
转载请注明来源:Web前端(W3Cways.com) - Web前端学习之路 » electron打开选择文件窗口,选中后返回file类型
分享到: 更多 (0)