文章首发于:clawhub.club


最近要做一个简单的桌面应用,需要操作文件,从网上找了一些例子,最后改改,测试测试。

进入页面:

2b1a18c56d1ec6eb28c006e1e2fed48.png

选择文件:

a85a803abf6bce31d9b0be98479d07c.png

展示文件:

397e23fea45be6934e2d3315b5fc396.png
架子用了https://github.com/demopark/electron-api-demos-Zh_CN

前端代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<template>
<div class="file-container">
<div class="file-selecter">
<!-- el-input -->
<el-input placeholder="请选择文件,支持多选" v-model="fileSelected" :disabled="true">
<template slot="prepend">
<el-button type="primary" @click="showOpenDialog()">选择文件</el-button>
</template>
</el-input>
</div>
<div class="file-datatable">
<div>共有 {{tableData.length}} 条记录</div>
<el-table v-loading="isLoading" element-loading-text="拼命加载中" :data="tableData" style="width: 100%">
<el-table-column prop="filePath" label="文件路径"> </el-table-column>
<el-table-column prop="fileSize" label="文件大小" fixed="right" width="100"> </el-table-column>
</el-table>
</div>
</div>
</template>

<script>
export default {
name: 'dialog',
data() {
return {
fileSelected: '',
isLoading: false,
tableData: []
}
},
methods: {
// 选择文件
showOpenDialog() {
const dialog = require('electron').remote.dialog
dialog.showOpenDialog({
title: '选择要上传的文件(支持多选)',
properties: ['openFile', 'multiSelections', 'showHiddenFiles']
}, (filePaths) => {
// filePaths:用户选择的文件路径的数组
console.log(filePaths)
// fs 模块提供了一个 API,用于以模仿标准 POSIX 函数的方式与文件系统进行交互。
const fs = require('fs')
for (const filePath of filePaths) {
console.log(filePath)
const stat = fs.statSync(filePath)
this.tableData.push({
filePath: filePath,
fileSize: stat.size
})
}
})
}
}
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.file {
&-container {
margin: 30px;
}

&-selecter {
padding: 10px;
}

&-datatable {
margin-top: 10px;
}
}
</style>

主要使用了electron的文件选择框,还有nodejs的fs组件,我是前端半吊子,各种地方抄代码运行,希望以后能像写服务端代码那样写前端。