如何用electron实现电脑间文件传输
时间: 2024-05-01 10:24:01 浏览: 15
可以通过 electron 的 `net` 模块来实现电脑间的文件传输。
具体实现步骤如下:
1. 在发送端(源电脑)启动一个服务端,监听一个指定的端口,等待接收端(目标电脑)的连接请求。
2. 在接收端启动一个客户端,连接发送端的服务端,并发送文件内容。
3. 在服务端接收到连接请求后,创建一个文件流,并将接收到的文件内容写入到文件流中,完成文件传输。
以下是一个简单的示例代码:
发送端:
```javascript
const { app, BrowserWindow, ipcMain, net } = require('electron')
const fs = require('fs')
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
mainWindow.loadFile('index.html')
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow)
ipcMain.on('send-file', (event, filePath, port) => {
const socket = net.connect(port, 'localhost', () => {
const readStream = fs.createReadStream(filePath)
readStream.on('data', (chunk) => {
socket.write(chunk)
})
readStream.on('end', () => {
socket.end()
})
})
socket.on('end', () => {
event.sender.send('file-sent')
})
})
```
接收端:
```javascript
const { app, BrowserWindow, ipcMain, net } = require('electron')
const fs = require('fs')
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
mainWindow.loadFile('index.html')
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow)
ipcMain.on('receive-file', (event, filePath, port) => {
const socket = net.connect(port, 'localhost', () => {
const writeStream = fs.createWriteStream(filePath)
socket.on('data', (chunk) => {
writeStream.write(chunk)
})
socket.on('end', () => {
writeStream.end()
event.sender.send('file-received')
})
})
})
```
在页面中,可以通过调用 `ipcRenderer.send('send-file', filePath, port)` 来实现发送端向接收端发送文件,或者调用 `ipcRenderer.send('receive-file', filePath, port)` 来实现接收端接收文件。其中,`filePath` 表示文件路径,`port` 表示端口号,需要在发送端和接收端保持一致。
需要注意的是,以上示例代码仅供参考,实际应用中还需要考虑一些安全性和稳定性的问题。