基于 Swoole 开发实时在线聊天室(十四):发送图片消息
由 学院君 创建于1年前, 最后更新于 1年前
版本号 #1
2055 views
0 likes
0 collects
上篇教程我们演示了聊天室中文本/表情消息发布,今天我们来看看图片消息如何发布。
前端交互代码
我们还是从前端组件开始,在聊天室组件 Chat.Vue 中,客户端图片发送核心逻辑位于 fileup 方法中,我们需要对原来的代码进行调整以适配基于 Laravel + Swoole 的后端接口:
fileup() {
const that = this;
const file1 = document.getElementById('inputFile').files[0];
if (file1) {
const formdata = new window.FormData();
formdata.append('file', file1);
formdata.append('api_token', this.auth_token);
formdata.append('roomid', that.roomid);
this.$store.dispatch('uploadImg', formdata);
const fr = new window.FileReader();
fr.onload = function () {
const obj = {
username: that.userid,
src: that.src,
img: fr.result,
msg: '',
roomid: that.roomid,
time: new Date(),
api_token: that.auth_token
};
socket.emit('message', obj);
};
fr.readAsDataURL(file1);
this.$nextTick(() => {
this.container.scrollTop = 10000;
});
} else {
console.log('必须有文件');
}