使用vue和websocket实现发送图片文件
时间: 2024-05-15 10:18:27 浏览: 99
利用Socket传送图片
5星 · 资源好评率100%
可以使用以下步骤:
1. 在Vue组件中,使用`input[type="file"]`元素让用户选择图片文件。
2. 创建WebSocket连接,并将所选的图片文件作为Blob对象发送到WebSocket服务器。
3. 在服务器端,接收Blob对象并将其转换为文件。
4. 将文件存储在服务器上,并向客户端发送成功响应。
以下是示例代码:
1. Vue组件中:
```
<template>
<div>
<input type="file" @change="onFileChange" />
</div>
</template>
<script>
export default {
data() {
return {
ws: null
};
},
created() {
this.connectWebSocket();
},
methods: {
connectWebSocket() {
this.ws = new WebSocket('ws://localhost:8080');
this.ws.binaryType = 'arraybuffer';
this.ws.onopen = () => console.log('WebSocket connected');
this.ws.onmessage = event => {
const data = JSON.parse(event.data);
if (data.type === 'success') {
console.log('Image uploaded successfully');
}
};
this.ws.onerror = error => console.error(error);
this.ws.onclose = () =>
console.log('WebSocket disconnected, trying to reconnect...');
},
onFileChange(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = () => {
const arrayBuffer = reader.result;
const blob = new Blob([new Uint8Array(arrayBuffer)], { type: file.type });
this.ws.send(blob);
};
reader.readAsArrayBuffer(file);
}
}
};
</script>
```
2. WebSocket服务器端:
```
const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', ws => {
console.log('WebSocket connection established');
ws.on('message', blob => {
const fileName = `${Date.now()}-${Math.floor(Math.random() * 1000)}${path.extname(file.name)}`;
const filePath = path.resolve(__dirname, 'uploads', fileName);
fs.writeFile(filePath, blob, error => {
if (error) {
console.error(error);
ws.send(JSON.stringify({ type: 'error', message: error.message }));
return;
}
console.log('File saved successfully');
ws.send(JSON.stringify({ type: 'success' }));
});
});
ws.on('close', () => console.log('WebSocket connection closed'));
});
```
阅读全文