用uniapp 及socket.io做一个简单聊天 升级 9

比这之前优化了以下功能
上线通知
群聊里适时显示在线人数
约请好友 通过好友通过socket 相应端自动变化
PC端可以拉取摄象头拍照
PC端可以录音发送
拉起摄象头发送录象

在这里插入图片描述

<template><view class=""><scroll-view scroll-y="true" class="scroll-box":style="{ height: `${windowObj.windowHeight - windowObj.statusBarHeight - 94}px` }":scroll-top="scrollHeight" @scrolltoupper="loadMores"><view class="group-box">在线{{userList.length}}人:<text class="group-member" v-for="(item, index) in userList" :key="index">{{item}} </text></view><view class="scroll-view"><view class="news-box" v-for="(item, index) in list" :key="index"><view class="message-type" v-if="['left', 'join', 'kick'].includes(item.type)">{{ item.content }} {{(formatDate(Date()))}}</view><image class="avatar" :class="[item.isMe ? 'is-me' : 'avatar-right']" :src="item.avatar"mode="aspectFill" v-if="!['kick', 'join', 'left'].includes(item.type)" @tap="kickopen(item)"></image><view class="message-box" :class="{ 'is-me': item.isMe }"v-if="!['kick', 'join', 'left'].includes(item.type)"><text class="message" v-if="item.type === 'text'"><image src="../../static/withdraw.png"style="width: 40rpx; height: 40rpx;position:relative;right:16rpx;bottom:1rpx;"mode="aspectFill" v-if="item.isMe && canwithdraw(item) && item.withdraw === 0"@tap="withdraw(item)"></image><text :selectable="true" @tap="copyBtnClick(item.content)" > {{formatMessage(item.content || '')}}</text></text><text class="message_img" v-if="['image', 'video', 'audio'].includes(item.type)"><template v-if="item.type === 'image'"><image class="message-image" :src="item.content" mode="aspectFill"@click="previewImage(item.content)" /></template><template v-if="item.type === 'video'"><video v-if="item.content" :src="item.content" controls></video></template><template v-if="item.type === 'audio'"><audio v-if="item.content" :src="item.content" controls ></audio></template><image src="../../static/withdraw.png" style="width: 50rpx; height: 50rpx" mode="aspectFill"v-if="item.isMe && canwithdraw(item) && item.withdraw === 0" @click="withdraw(item)"></image></text></view></view></view></scroll-view><view class="base-btn" :class="{ 'base-btn-popup-open': isPopupOpen || isPopupAudioOpen }"><view class="base-con unify-flex"><view @tap="more"><image src="../../static/chat/more.png" style="width: 50rpx; height: 50rpx"></image></view><input class="input-text" type="text" :value="inputValue" placeholder="说些什么吧" @input="getInput"@confirm="tapTo(2)" /><view @click="tapTo(2)"><image src="../../static/chat/chat.png" style="width: 50rpx; height: 50rpx"></image></view></view></view><uni-popup ref="popup" type="bottom" :style="{ height: '200rpx' }" @change="onPopupChange"><view class="popup-content":style="{ width: '100%', backgroundColor: '#fff', height: '200rpx', overflowY: 'scroll' }"><view class="popup-items"><view class="popup-item" v-if="type === 'group'" @tap="adduserTogroup"><image src="../../static/chat/add.png" style="width: 50rpx; height: 50rpx"></image><text>添加</text></view><view class="popup-item" @click="chooseFile"><image src="../../static/chat/pic.png" style="width: 50rpx; height: 50rpx"></image><text>图片</text></view><view class="popup-item" @tap="audio"><image src="../../static/chat/audio.png" style="width: 50rpx; height: 50rpx"></image><text>音频</text></view><view class="popup-item" @tap="openCamera"><image src="../../static/chat/video.png" style="width: 50rpx; height: 50rpx"></image><text>视频</text></view><view class="popup-item" @tap="groupdetail"><image src="../../static/chat/detail.png" style="width: 50rpx; height: 50rpx"></image><text>详情</text></view><view class="popup-item" v-if="type === 'group'" @tap="quitgroup"><image src="../../static/chat/exit-group.png" style="width: 50rpx; height: 50rpx"></image><text>退群</text></view></view></view></uni-popup><uni-popup ref="popupAudio" type="bottom" :style="{ height: '200rpx' }" @change="onPopupAudioChange"><view class="popup-content":style="{ width: '100%', backgroundColor: '#fff', height: '200rpx', overflowY: 'scroll' }"><view class="popup-item" @click="startRecording"><image src="../../static/chat/beginaudio.png" style="width: 50rpx; height: 50rpx"></image><text>录音</text></view><view class="popup-item" @click="stopRecording"><image src="../../static/chat/send.png" style="width: 50rpx; height: 50rpx"></image><text>发送录音</text></view><!-- 		<view class="popup-item" @tap="playRecording"><image src="../../static/chat/play.png" style="width: 50rpx; height: 50rpx"></image><text>播放</text></view> --><!-- 	<view class="popup-item" @tap="upsong"><image src="../../static/chat/send.png" style="width: 50rpx; height: 50rpx"></image><text>发送</text></view> --><view class="popup-item" @tap="exitchat"><image src="../../static/chat/exit.png" style="width: 50rpx; height: 50rpx"></image><text>退出</text></view></view></uni-popup><uni-popup ref="popupkick" type="bottom" :style="{ height: '200rpx' }" @change="onPopupAudioChange"><view class="popup-content":style="{ width: '100%', backgroundColor: '#fff', height: '200rpx', overflowY: 'scroll' }"><view class="popup-item" @click="kick('kick')"><image src="../../static/chat/kickp.png" style="width: 50rpx; height: 50rpx"></image><text>踢人</text></view><view class="popup-item" @click="kick('black')"><image src="../../static/chat/black.png" style="width: 50rpx; height: 50rpx"></image><text>拉黑</text></view><view class="popup-item" @tap="detail"><image src="../../static/chat/detail.png" style="width: 50rpx; height: 50rpx"></image><text>详情</text></view></view></uni-popup></view>
</template>
<script>import io from 'socket.io-client';import config from '@/config/config.js';import {mapState,mapActions} from 'vuex';import {v4 as uuidv4} from 'uuid';import {getCurrentDateTime} from '@/common/dateFormatter.js'import { handleClipboard } from '@/common/clipboardone.js';export default {data() {return {name: '',inputValue: '',list: [],image: '',scrollHeight: 0,userList: '',type: '',socket: null,messages: [],groupName: '',tid: '',toid: 0,receiver_type: '',isPopupOpen: false,isPopupAudioOpen: false,selectedFilePath: '',group_owner_id: 0, //群主idfid: '',to_id: 0,recordingPath: '', // 用于存储录音文件的路径isRecording: false,mediaRecorder: null,audioChunks: []};},computed: {...mapState(['user']),windowObj() {let obj;uni.getSystemInfo({success: (res) => {obj = res;}});return obj;}},watch: {isPopupOpen(newValue) {if (!newValue) {this.$refs.popup.close();}},isPopupAudioOpen(newValue) {if (!newValue) {this.$refs.popupAudio.close();}}},async onLoad(q) {let _ = this;try {if (q && q.id != undefined) {this.groupName = q.id;this.tid = q.tid;this.to_id = q.to_idthis.receiver_type = q.type;this.type = this.receiver_typeuni.setNavigationBarTitle({title: q.type == 'group' ? '[群聊] '+q.to_name: '[私聊] '+q.to_name});if (q.type == 'group') {//将q.id的前面g_去掉let newid = q.id.replace('g_', '')//获到了当前群的群主idlet re = await _.getGroupOwner(newid)this.group_owner_id = re.data.data.owner_id}let re = await _.checkFriend(q.id);if (re == true) {_.joinGroup(this.groupName);} else {uni.navigateTo({url: '/pages/index/friends'});}} else {uni.navigateTo({url: '/pages/index/friends'});}} catch (e) {uni.navigateTo({url: '/pages/index/friends'});}},onUnload() {this.socket.close();},onShow() {this.fetchUser();},mounted() {this.initChatLog();this.socket = io(config.apiBaseUrl);this.socket.on('connect', () => {console.log('Socket connected:', this.socket.id);});this.socket.on('disconnect', () => {console.log('Socket disconnected');});let heartbeatInterval;let reconnectAttempts = 0;const maxReconnectAttempts = 10;const startHeartbeat = () => {heartbeatInterval = setInterval(() => {if (this.socket.connected) {this.socket.emit('heartbeat');console.log('heartbeat')} else {reconnectSocket();}}, 120000); // 1分钟};const reconnectSocket = () => {if (reconnectAttempts < maxReconnectAttempts) {this.socket.connect();reconnectAttempts++;} else {clearInterval(heartbeatInterval);uni.showModal({title: '连接失败',content: '无法连接到服务器,是否手动重新连接?',confirmText: '重新连接',cancelText: '取消',success: (res) => {if (res.confirm) {reconnectAttempts = 0;this.socket.connect();startHeartbeat();}}});}};startHeartbeat();this.socket.on('reconnect', () => {console.log('Socket重新连接成功');reconnectAttempts = 0;});this.socket.on('message', (msg) => {if (msg.type == 'broadcast') {return;}if (msg.type == 'widthdraw') {//查出 msg.sn 将此记录信息改为撤回//console.log(msg);this.list.forEach((item, index) => {if (item.sn == msg.content) {this.list[index].content = '[消息已撤回]';this.list[index].type = 'text';this.list[index].withdraw = 1;this.widthdrawRow(item.sn)}});return;}let msgs = {sn: msg.sn,name: msg.user_name,avatar: msg.avatar,isMe: msg.fid == this.user.id ? true : false,content: msg.content,type: msg.type,sn: msg.sn,createat: Math.floor(Date.now() / 1000),time: Date.now(),withdraw: 0,toid: msg.fid};this.list.push(msgs);this.setScrollTop();});// 监听 'userList' 事件this.socket.on('userList', (users) => {this.userList = users; // 更新 userList 变量console.log('- 当前群用户 -')console.log(this.userList)});},methods: {...mapActions(['fetchUser', 'logout', 'fetchGroups']),formatDate() {return getCurrentDateTime();},kickopen(item) {this.name = item.namethis.toid = item.toidif (!item.isMe) {this.$refs.popupkick.open()}},getGroupOwner(id) {//接口 group 提交id 获取到群的信息const token = uni.getStorageSync('token');return new Promise((resolve, reject) => {uni.request({url: `${config.apiBaseUrl}/group`,method: 'GET',header: {Authorization: `Bearer ${token}`},data: {id: id},success: (res) => {resolve(res)},fail: (err) => {reject(err)}});})},async widthdrawRow(sn) {const token = uni.getStorageSync('token');if (!token) return;try {const [error, response] = await uni.request({url: `${config.apiBaseUrl}/withdraw`,method: 'GET',header: {Authorization: `Bearer ${token}`},data: {sn: sn}});if (error) {throw new Error(`Request failed with error: ${error}`);}if (response.data.code === 0) {return true;} else {return false;}} catch (error) {return false;}},adduserTogroup() {this.isPopupOpen=falseuni.navigateTo({url: '/pages/index/addfriend?groupId=' + this.tid});},kick(type) {//将用户踢出去if (this.group_owner_id != this.fid) {//这样才能踢	if (type == 'kick') {this.kickUser(this.name)} else {//拉黑this.kickUser(this.name, 'black')//再拉黑}} else {uni.showToast({title: '不能对自己操作'})}},detail() {uni.navigateTo({url: '/pages/index/about?id=' + this.to_id});},groupdetail() {let groupid = this.groupName.replace('g_', '')if (this.type == 'group') {uni.navigateTo({url: '/pages/index/groupdetail?id=' + groupid});} else {uni.navigateTo({url: '/pages/index/about?id=' + this.to_id});}},async quitgroup() {console.log(this.group_owner_id)console.log(this.user.id)if (this.group_owner_id == this.user.id) {//主人不能退群uni.showToast({title: '主人不能退群'})return}let groupid = this.groupName.replace('g_', '')//调用接口退出 接口名为leavgroup 	const token = uni.getStorageSync('token');if (!token) return;try {const [error, response] = await uni.request({url: `${config.apiBaseUrl}/leavgroup`,method: 'GET',header: {Authorization: `Bearer ${token}`},data: {groupid}});if (error) {throw new Error(`Request failed with error: ${error}`);}console.log(response)if (response.data.code === 0) {uni.navigateTo({url: '/pages/index/friends'})return true;} else {return false;}} catch (error) {return false;}},onPopupChange() {if (this.isPopupOpen == true) {this.isPopupOpen = false;}},playVoice(url) {// 创建音频对象const audio = new Audio(url);// 播放音频audio.play().then(() => {console.log('音频开始播放');}).catch((error) => {console.error('音频播放失败:', error);});// 监听音频播放结束事件audio.onended = () => {console.log('音频播放结束');};},onPopupAudioChange() {if (this.isPopupOpen == true) {this.isPopupOpen = false;}this.recordingPath = '';},audio() {this.$refs.popup.close();this.$refs.popupAudio.open();this.isPopupOpen = true;},exitchat() {this.$refs.popupAudio.close();},async 	startRecording() {try {if(this.isRecording){uni.showToast({title: '正在录音中',icon: 'none',duration: 2000});return;}const stream = await navigator.mediaDevices.getUserMedia({ audio: true });this.mediaRecorder = new MediaRecorder(stream);//console.log(this.mediaRecorder);this.mediaRecorder.ondataavailable = (event) => {this.audioChunks.push(event.data);};this.mediaRecorder.onstop  = async () => {const audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' });const url = URL.createObjectURL(audioBlob);this.selectedFilePath = url;// 创建一个提示框const confirmResult = await new Promise((resolve) => {uni.showModal({title: '录音完成',content: '是否上传录音?',confirmText: '上传',cancelText: '取消',success: (res) => {resolve(true);}});});// 如果用户选择取消,则不继续处理if (!confirmResult) {this.audioChunks = [];this.isRecording = false;return;}else{this.uploadAvatar('audio');}this.isPopupOpen=false;this.isRecording=false;// 清理本地声音stream.getTracks().forEach(track => track.stop());URL.revokeObjectURL(url);};this.mediaRecorder.start();this.isRecording = true;} catch (error) {console.error('获取麦克风权限失败:', error);}},async stopRecording() {//console.log('停止录音')if (this.mediaRecorder) {this.mediaRecorder.stop();this.isRecording = false;this.popupAudio=false;}else{uni.showToast({title: '没有录音',icon: 'none'});}},uploadAudio(audioBlob) {const formData = new FormData();formData.append('audio', audioBlob, 'recorded_audio.wav');console.log(URL.createObjectURL(audioBlob))const token = uni.getStorageSync('token');uni.uploadFile({url: `${config.apiBaseUrl}/upload`,filePath: URL.createObjectURL(audioBlob),name: 'avatar',header: {Authorization: `Bearer ${token}`},// formData: formData,success: (uploadFileRes) => {const response = JSON.parse(uploadFileRes.data);if (response.code == 0) {const avatarUrl = response.data;this.sendMessage(avatarUrl, 'audio');}},fail: (err) => {//console.error('上传失败:', err);console.error('Failed to upload avatar:', error);uni.showToast({title: '上传失败',icon: 'none'});}});},playRecording() {if (this.recordingPath) {const innerAudioContext = uni.createInnerAudioContext();innerAudioContext.src = this.recordingPath;innerAudioContext.onPlay(() => {console.log('开始播放录音');});innerAudioContext.onError((res) => {console.error('播放录音失败:', res);});innerAudioContext.play();} else {uni.showToast({title: '没有可播放的录音',icon: 'none'});}},upsong() {const token = uni.getStorageSync('token');uni.uploadFile({url: `${config.apiBaseUrl}/upload`,filePath: this.selectedFilePath,name: 'avatar',header: {Authorization: `Bearer ${token}`},success: async (uploadFileRes) => {const response = JSON.parse(uploadFileRes.data);if (response.code == 0) {const avatarUrl = response.data;this.sendMessage(avatarUrl, type);}},fail: (error) => {console.error('Failed to upload avatar:', error);uni.showToast({title: '上传失败',icon: 'none'});}});  },more() {this.$refs.popup.open();this.isPopupOpen = true;},openCamera() {if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then((stream) => {// 创建视频元素const video = document.createElement('video');video.srcObject = stream;video.autoplay = true;// 创建容器const container = document.createElement('div');container.style.position = 'fixed';container.style.top = '0';container.style.left = '0';container.style.width = '100%';container.style.height = '100%';container.style.backgroundColor = 'rgba(0,0,0,0.8)';container.style.zIndex = '9999';container.appendChild(video);document.body.appendChild(container);// 创建录制器const mediaRecorder = new MediaRecorder(stream);let chunks = [];mediaRecorder.ondataavailable = (e) => {chunks.push(e.data);};mediaRecorder.onstop = () => {const blob = new Blob(chunks, { type: 'video/webm' });chunks = [];const videoUrl = URL.createObjectURL(blob);this.selectedFilePath = videoUrl;this.uploadAvatar('video');};// 开始录制mediaRecorder.start();// 添加上传按钮const uploadButton = document.createElement('button');uploadButton.textContent = '停止录制并上传';uploadButton.style.position = 'absolute';uploadButton.style.bottom = '10px';uploadButton.style.left = '50%';uploadButton.style.transform = 'translateX(-50%)';uploadButton.onclick = () => {mediaRecorder.stop();stream.getTracks().forEach(track => track.stop());document.body.removeChild(container);};container.appendChild(uploadButton);}).catch((error) => {console.error('无法访问摄像头:', error);uni.showToast({title: '无法访问摄像头',icon: 'none'});});} else {uni.showToast({title: '您的设备不支持摄像头',icon: 'none'});}// if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {// 			navigator.mediaDevices.getUserMedia({ video: true })// 				.then((stream) => {// 					// 创建一个 video 元素来显示摄像头画面// 					const video = document.createElement('video');// 					video.srcObject = stream;// 					video.autoplay = true;// 					// 创建一个容器来放置 video 元素// 					const container = document.createElement('div');// 					container.style.position = 'fixed';// 					container.style.top = '0';// 					container.style.left = '0';// 					container.style.width = '100%';// 					container.style.height = '100%';// 					container.style.backgroundColor = 'rgba(0,0,0,0.8)';// 					container.style.zIndex = '9999';// 					container.appendChild(video);// 					document.body.appendChild(container);// 					// 创建一个 canvas 元素用于捕获视频帧// 					const canvas = document.createElement('canvas');// 					// 添加一个按钮来关闭摄像头并上传图片// 					const closeButton = document.createElement('button');// 					closeButton.textContent = '拍照并上传';// 					closeButton.style.position = 'absolute';// 					closeButton.style.bottom = '10px';// 					closeButton.style.left = '50%';// 					closeButton.style.transform = 'translateX(-50%)';// 					closeButton.onclick = () => {// 						// 捕获当前视频帧// 						canvas.width = video.videoWidth;// 						canvas.height = video.videoHeight;// 						canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);// 						// 将 canvas 转换为 Blob// 						canvas.toBlob((blob) => {// 							// 停止所有视频轨道// 							stream.getTracks().forEach(track => track.stop());// 							// 移除容器// 							document.body.removeChild(container);// 							// 创建一个临时的 URL// 							const imageUrl = URL.createObjectURL(blob);// 							// 将Blob转换为File对象,并设置.mp4后缀// 							//const file = new File([blob], 'captured_video.mp4', { type: 'video/mp4' });// 							// 创建新的临时URL// 							// 设置 selectedFilePath 并调用 uploadAvatar// 							this.selectedFilePath = imageUrl;// 							this.uploadAvatar('video');// 							// 清理临时 URL// 							URL.revokeObjectURL(imageUrl);// 						}, 'image/jpeg');// 					};// 					container.appendChild(closeButton);// 				})// 				.catch((error) => {// 					console.error('无法访问摄像头:', error);// 					uni.showToast({// 						title: '无法访问摄像头',// 						icon: 'none',// 						duration: 2000// 					});// 				});// 		} else {// 			uni.showToast({// 				title: '您的设备不支持摄像头访问',// 				icon: 'none',// 				duration: 2000// 			});// 		}},withdraw(item) {let _ = this;const currentTime = Date.now();const messageTime = parseInt(item.time);const oneMinute = config.minute; // 60 * 1000 millisecondsif (currentTime < (messageTime + oneMinute)) {uni.showModal({title: '提示',content: '确认删除该条信息吗?',success: function(res) {if (res.confirm) {// 执行确认后的操作if (_.canwithdraw(item)) {const messageData = {sn: uuidv4(),group_name: _.groupName,avatar: _.user.avatar_url,content: item.sn,user_name: _.user.username,type: 'widthdraw',fid: _.user.id,tid: _.tid,created_at: _.getCurrentTimeToMinute(),receiver_type: _.receiver_type};_.socket.emit('sendMessage', messageData);} else {uni.showToast({title: '超过一分钟不能撤回',icon: 'none'});}} else {// 执行取消后的操作}}});}},canwithdraw(item) {const currentTime = Date.now();const messageTime = parseInt(item.time);const oneMinute = config.minute; // 60 * 1000 millisecondsif (currentTime > (messageTime + oneMinute)) {return false;} else {return true;}},getCurrentTimeToMinute() {const now = new Date();// 使用 Intl.DateTimeFormat 格式化日期和时间const dateFormatter = new Intl.DateTimeFormat('default', {year: 'numeric',month: '2-digit',day: '2-digit',hour: '2-digit',minute: '2-digit',hour12: false});// 格式化日期时间并返回return dateFormatter.format(now).replace(',', '');},async checkFriend(id) {const token = uni.getStorageSync('token');if (!token) return;let data = {id};try {const [error, response] = await uni.request({url: `${config.apiBaseUrl}/checkFriend`,method: 'GET',header: {Authorization: `Bearer ${token}`},data: {Id: id}});if (error) {throw new Error(`Request failed with error: ${error}`);}if (response.data.code === 0) {return true;} else {return false;}} catch (error) {return false;}},joinGroup() {this.socket.emit('joinGroup', {groupName: this.groupName,userName: this.user.username,userId: this.user.id});},tapTo(state) {let message = this.inputValue;if (message == '') {uni.showToast({title: '请输入聊天内容',icon: 'error'});return;}this.sendMessage(message);},getInput(e) {this.inputValue = e.detail.value;},initChatLog() {console.log('-initChatLog-')let _ = this;this.list = [];//接口 group 提交id 获取到群的信息const token = uni.getStorageSync('token');return new Promise((resolve, reject) => {uni.request({url: `${config.apiBaseUrl}/getMessages`,method: 'GET',header: {Authorization: `Bearer ${token}`},data: {receiver_type: _.receiver_type,tid: _.to_id   // 修复Bug, 原来这里写的是 _.tid},success: (res) => {resolve(res)console.log('-getMessages-')console.log(res.data.data.messages)this.list = res.data.data.messagesthis.list.forEach((item, index) => {this.list[index].isMe = item.fid == this.user.id ? true :false;this.list[index].toid = item.fid});},fail: (err) => {reject(err)}});})},async sendMessage(message, type = 'text') {this.$refs.popup.close();const messageData = {sn: uuidv4(),group_name: this.groupName,avatar: this.user.avatar_url,content: message,user_name: this.user.username,type: type,fid: this.user.id,tid: this.to_id, // 原来this.tid写错了  created_at: this.getCurrentTimeToMinute(),receiver_type: this.receiver_type};this.socket.emit('sendMessage', messageData);this.inputValue = '';if (type == 'image' || type == 'audio' || type == 'video' || type == 'text') {const token = uni.getStorageSync('token');try {const [error, response] = await uni.request({url: `${config.apiBaseUrl}/addmessage`,method: 'POST',header: {Authorization: `Bearer ${token}`},data: messageData});if (error) {throw new Error(`Request failed with error: ${error}`);}} catch (error) {}}this.$nextTick(() => {this.setScrollTop();});},async kickUser(name, type = 'kick') {console.log("groupname", this.groupName)console.log("name", name)console.log("type", type)if (type == 'kick') {this.socket.emit('kickUser', {groupName: this.type == 'group' ? this.groupName : this.groupName.replace('g_', ''),userName: name});} else {this.socket.emit('kickUser', {groupName: this.type == 'group' ? this.groupName : this.groupName.replace('g_', ''),userName: name});//拉黑let group_id = this.groupName.replace('g_', '')if (this.type != 'group') {group_id = 0}//调用black接口进行拉黑,拦黑完成让界面跳到friendsconst token = uni.getStorageSync('token');try {const [error, response] = await uni.request({url: `${config.apiBaseUrl}/black`,method: 'POST',header: {Authorization: `Bearer ${token}`},data: {name,group_id}});if (error) {throw new Error(`Request failed with error: ${error}`);}if (response.data.data.code == 0) {if (this.type == 'user') {uni.navigateTo({url: '/pages/index/friends'})}}} catch (error) {}}},setScrollTop() {this.$nextTick(() => {let query = uni.createSelectorQuery().in(this);query.select('.scroll-view').boundingClientRect((rect) => {if (rect) {this.scrollHeight = rect.height;}}).exec();});},chooseFile() {// 检查是否为PC端const isPC = /Windows|Mac|Linux/.test(navigator.userAgent);if (isPC) {// PC端,调用摄像头拍照if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {// 创建视频元素const video = document.createElement('video');video.srcObject = stream;video.autoplay = true;// 创建容器const container = document.createElement('div');container.style.position = 'fixed';container.style.top = '0';container.style.left = '0';container.style.width = '100%';container.style.height = '100%';container.style.backgroundColor = 'rgba(0,0,0,0.8)';container.style.zIndex = '9999';container.appendChild(video);document.body.appendChild(container);// 添加拍照按钮const captureButton = document.createElement('button');captureButton.textContent = '拍照';captureButton.style.position = 'absolute';captureButton.style.bottom = '10px';captureButton.style.left = '30%';captureButton.style.transform = 'translateX(-50%)';captureButton.onclick = () => {// 创建canvas并捕获当前视频帧const canvas = document.createElement('canvas');canvas.width = video.videoWidth;canvas.height = video.videoHeight;canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);// 将canvas转换为Blobcanvas.toBlob((blob) => {// 停止所有视频轨道stream.getTracks().forEach(track => track.stop());// 移除容器document.body.removeChild(container);// 创建临时URL并上传const imageUrl = URL.createObjectURL(blob);this.selectedFilePath = imageUrl;this.uploadAvatar('image');// 清理临时URLURL.revokeObjectURL(imageUrl);}, 'image/jpeg');};container.appendChild(captureButton);// 添加取消按钮const cancelButton = document.createElement('button');cancelButton.textContent = '取消';cancelButton.style.position = 'absolute';cancelButton.style.bottom = '10px';cancelButton.style.left = '70%';cancelButton.style.transform = 'translateX(-50%)';cancelButton.onclick = () => {// 停止所有视频轨道stream.getTracks().forEach(track => track.stop());// 移除容器document.body.removeChild(container);// 继续执行选择文件的逻辑this.showFileChooseOptions();};container.appendChild(cancelButton);}).catch((error) => {console.error('无法访问摄像头:', error);uni.showToast({title: '无法访问摄像头',icon: 'none'});// 如果无法访问摄像头,继续执行选择文件的逻辑this.showFileChooseOptions();});} else {uni.showToast({title: '您的设备不支持摄像头',icon: 'none'});// 如果设备不支持摄像头,继续执行选择文件的逻辑this.showFileChooseOptions();}} else {// 非PC端,直接执行选择文件的逻辑this.showFileChooseOptions();}},showFileChooseOptions(){uni.showActionSheet({itemList: ['拍照', '从相册选择'],success: (res) => {if (res.tapIndex === 0) {this.takePhoto();} else if (res.tapIndex === 1) {this.selectImage();}},fail: (error) => {console.error('Failed to show action sheet:', error);uni.showToast({title: '操作失败',icon: 'none'});}});},takePhoto() {uni.chooseImage({count: 1,sourceType: ['camera'],success: async (res) => {this.selectedFilePath = res.tempFilePaths[0];await this.uploadAvatar('image');},fail: (error) => {console.error('Failed to take photo:', error);uni.showToast({title: '拍照失败',icon: 'none'});}});},selectImage() {uni.chooseImage({count: 1,sourceType: ['album'],success: async (res) => {this.selectedFilePath = res.tempFilePaths[0];await this.uploadAvatar('image');},fail: (error) => {console.error('Failed to select image:', error);uni.showToast({title: '选择图片失败',icon: 'none'});}});},previewImage(url) {uni.previewImage({urls: [url] // 需要预览的图片http链接列表});},async uploadAvatar(type) {if (!this.selectedFilePath) {uni.showToast({title: '请选择文件',icon: 'none'});return;}const token = uni.getStorageSync('token');uni.uploadFile({url: `${config.apiBaseUrl}/upload`,filePath: this.selectedFilePath,name: 'avatar',header: {Authorization: `Bearer ${token}`},success: async (uploadFileRes) => {const response = JSON.parse(uploadFileRes.data);if (response.code == 0) {const avatarUrl = response.data;this.sendMessage(avatarUrl, type);}},fail: (error) => {console.error('Failed to upload avatar:', error);uni.showToast({title: '上传失败',icon: 'none'});}});},copyBtnClick(data) {handleClipboard( // 这是 实现向剪切板 写入内容的代码, data 就是传入的要写入剪切板的内容// 写入剪切板data,  event,() => {uni.showToast({title: '已复制到剪切板',});},() => {uni.showToast({title: '复制失败',});});},formatMessage(content) {// Detect URLs and format them as linksconst urlRegex = /(https?:\/\/[^\s]+)/g;content = content.replace(urlRegex, '<a href="$1" target="_blank" style="color:blue;">$1</a>');return content.replace(/\n/g, '<br>');},detectCode(content) {// Basic check to see if the content is likely code (this can be improved)const codeKeywords = ['function', 'const', 'let', 'var', 'if', 'else', '{', '}', '=', '=>'];return codeKeywords.some(keyword => content.includes(keyword)) || /[<>&]/.test(content);},escapeHtml(content) {// Escape HTML to prevent it from being rendered as actual HTMLreturn content.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");}}};
</script>
<style lang="scss" scoped>@import url('static/iconfont.css');.base-btn {position: fixed;width: 100%;height: 50px;bottom: var(--window-bottom);left: 0;justify-content: space-between;background-color: #ffffff;transition: bottom 0.3s;}.base-btn-popup-open {bottom: 200rpx;/* 调整为 popup 高度 */}.base-con {margin-top: 7.5px;display: flex;height: inherit;align-items: center;justify-content: space-between;}.send-image {width: 35px;line-height: 35px;background-color: #ffb967;border-radius: 50%;text-align: center;color: #ffffff;font-size: 30rpx;}.input-text {width: 58%;height: 35px;background-color: #f2f2f2;border-radius: 8px;padding: 0 15px;}.send-input {width: 64px;line-height: 35px;text-align: center;background-color: #ffb967;border-radius: 8px;color: #ffffff;}.scroll-view,.base-con {margin: 0 15px;}.avatar {width: 32px;height: 32px;border-radius: 50%;float: left;margin-top: 20px;}.avatar-right {margin-right: 10px;}.message-box {max-width: 76%;display: inline-block;word-wrap: break-word;/* 控制消息框换行 */}.message {font-size: 30rpx;background-color: #e6e6e6;padding: 10px;float: left;border-radius: 8px;overflow: hidden;word-break: break-all;white-space: pre-wrap;margin-top: 10px;width: 100%;}.message_img {font-size: 0rpx;background-color: lightgray;padding: 10px;float: left;border-radius: 8px;overflow: hidden;word-break: break-all;white-space: pre-wrap;margin-top: 5px;}.message-image {width: 80px;height: 130px;padding: 15px 0;border-radius: 8px;overflow: hidden;}.news-box::after {content: '';display: block;clear: both;}.news-box:last-child .message {margin-bottom: 20px;}.is-me {float: right;margin-left: 10px;}.message-type {text-align: center;color: #aaa;/* 字体颜色变淡 */font-size: 20rpx;/* 字体小一号 */margin-top: 10px;}.group-box {color: #727172;/* 字体颜色变淡 */font-size: 26rpx;/* 字体小一号 */margin: 6px 0 0 6px;}.group-member {margin-right: 4px;}.popup-content {display: flex;justify-content: center;/* 居中对齐内容 */align-items: center;/* 垂直居中对齐 */}.popup-items {display: flex;width: 100%;flex-wrap: wrap;/* 允许换行 */justify-content: space-around;/* 平均分配空间 */padding: 10rpx;/* 可选的内边距 */}.popup-item {flex: 1 1 10%;/* 每个图片占据 20% 的宽度,支持换行 */display: flex;flex-direction: column;/* 垂直布局 */justify-content: center;align-items: center;margin: 5rpx;/* 图片间距 */}.popup-image {width: 80%;/* 图片宽度占父容器的 80% */height: auto;/* 高度自动,以保持宽高比 */object-fit: cover;/* 确保图片在框中完全填充 */}.username {font-size: 20rpx;color: #666;margin-top: 5px;text-align: center;}
</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1542793.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

Java启动Tomcat: Can‘t load IA 32-bit .dll on a AMD 64-bit platform报错问题解决

&#x1f3ac; 鸽芷咕&#xff1a;个人主页 &#x1f525; 个人专栏: 《C干货基地》《粉丝福利》 ⛺️生活的理想&#xff0c;就是为了理想的生活! 专栏介绍 在软件开发和日常使用中&#xff0c;BUG是不可避免的。本专栏致力于为广大开发者和技术爱好者提供一个关于BUG解决的经…

树莓派pico上手

0 介绍 不同于作为单板计算机的树莓派5&#xff0c;树莓派 pico 是一款低成本、高性能的微控制器板&#xff0c;具有灵活的数字接口。主要功能包括&#xff1a; 英国树莓派公司设计的 RP2040 微控制器芯片双核 Arm Cortex M0 处理器&#xff0c;弹性的时钟频率高达 133 MHz26…

Tomcat 靶场攻略

CVE-2017-12615 步骤一&#xff1a;环境搭建 cd vulhub/tomcat/CVE-2017-12615 docker-compose up -d docker ps 步骤二&#xff1a;漏洞复现 http://192.168.10.190:8080/ 步骤二&#xff1a;首页进行抓包 Tomcat允许适⽤put⽅法上传任意⽂件类型&#xff0c;但不允许js…

小程序-基础知识1

Mustache语法 小程序和vue一样提供了插值语法 但是小程序不能调用方法{{xxxx()}} hidden属性 hidden是所有组件都默认拥有的属性&#xff0c; hidden与wx:if的区别&#xff1a; wx:if是控制组件是否渲染,hidden控制显示或隐藏是通过添加hidden属性。 wx:for 除了可以遍历…

HCIA--实验十九:配置接口DCHP

一、实验内容 1.需求/要求&#xff1a; 通过一台5700交换机和一台PC&#xff0c;通过在交换机的接口上配置接口DHCP来实现PC自动获取ip地址。 二、实验过程 1.拓扑图&#xff1a; 2.步骤&#xff1a; 1.给vlan10配置ip地址&#xff0c;进入vlan10开启接口的DHCP&#xff1…

Java数据库连接——JDBC

目录 1、JDBC简介 2、JDBC应用 2.1 建立数据库连接 2.1.1 DriverManager静态方法获取连接 2.1.2 DataSource对象获取 2.2 获取SQL执行对象 2.2.1 SQL注入 2.2.2 Statement(执行静态SQL) 2.2.3 PreparedStatement(预处理的SQL执行对象) 2.3 执行SQL并返回结果 2.4 关…

【笔记】材料分析测试:晶体学

晶体与晶体结构Crystal and Crystal Structure 1.晶体主要特征 固态物质可以分为晶态和非晶态两大类&#xff0c;分别称为晶体和非晶体。 晶体和非晶体在微观结构上的区别在于是否具有长程有序。 晶体&#xff08;长程有序&#xff09;非晶&#xff08;短程有序&#xff09…

机器人机构、制造

简单整理一下&#xff0c;在学习了一些运动学和动力学之类的东西&#xff0c;简单的整合了一些常用的机械结构和图片。 1.电机&#xff1a; 市面上的电机有&#xff1a;直流电机&#xff0c;交流电机&#xff0c;舵机&#xff0c;步进电机&#xff0c;电缸&#xff0c;无刷电…

李宏毅结构化学习 03

文章目录 一、Sequence Labeling 问题概述二、Hidden Markov Model(HMM)三、Conditional Random Field(CRF)四、Structured Perceptron/SVM五、Towards Deep Learning 一、Sequence Labeling 问题概述 二、Hidden Markov Model(HMM) 上图 training data 中的黑色字为x&#xff…

基于单片机的水位检测系统仿真

目录 一、主要功能 二、硬件资源 三、程序编程 四、实现现象 一、主要功能 基于51单片机&#xff0c;DHT11温湿度检测&#xff0c;水位检测&#xff0c;通过LCD1602显示&#xff0c;超过阈值报警&#xff0c;继电器驱动电机转动。通过矩阵按键切换选择设置各项参数阈值。 …

【Linux】通过内核以太层可查看应用程序运行时访问外网情况

比如&#xff0c;SourceInsight3.exe从外网接收信息&#xff1a; 下边是运行firefox时内核打印的日志&#xff0c;可以看到浏览器运行时调用了很多的操作系统内核系统调用&#xff0c;比如&#xff1a;文件读写、网络数据包的收发等等&#xff0c;其实这些日志还并不全&#x…

基于Ambari搭建hadoop生态圈+Centos7安装教程(还没写完,等明天补充完整)

当我们学习搭建hadoop的时候&#xff0c;未免也会遇见很多繁琐的事情&#xff0c;比如很多错误&#xff0c;需要解决。在以后公司&#xff0c;也不可能让你一个一个搭建hadoop&#xff0c;成千上万的电脑&#xff0c;你再一个个搭建&#xff0c;一个个报错&#xff0c;而且每台…

数据处理与统计分析篇-day08-apply()自定义函数与分组操作

一. 自定义函数 概述 当Pandas自带的API不能满足需求, 例如: 我们需要遍历的对Series中的每一条数据/DataFrame中的一列或一行数据做相同的自定义处理, 就可以使用Apply自定义函数 apply函数可以接收一个自定义函数, 可以将Series对象的逐个值或DataFrame的行/列数据传递给自…

K8s 之微服务的定义及详细资源调用案例

什么是微服务 用控制器来完成集群的工作负载&#xff0c;那么应用如何暴漏出去&#xff1f; 需要通过微服务暴漏出去后才能被访问 Service是一组提供相同服务的Pod对外开放的接口。借助Service&#xff0c;应用可以实现服务发现和负载均衡。service默认只支持4层负载均衡能力&…

OpenCV特征检测(10)检测图像中直线的函数HoughLinesP()的使用

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 在二值图像中使用概率霍夫变换查找线段。 该函数实现了用于直线检测的概率霍夫变换算法&#xff0c;该算法在文献 181中有所描述。 HoughLines…

JavaEE: 深入探索TCP网络编程的奇妙世界(五)

文章目录 TCP核心机制TCP核心机制六: 拥塞控制为什么要有拥塞控制?动态调整的拥塞控制拥塞控制中,窗口大小具体的变化过程 TCP核心机制七: 延时应答TCP核心机制八: 捎带应答 TCP核心机制 前一篇文章 JavaEE: 深入探索TCP网络编程的奇妙世界(四) 书接上文~ TCP核心机制六: 拥…

Parallels Desktop 20 for Mac 推出:完美兼容 macOS Sequoia 与 Win11 24H2

Parallels Desktop 20 for Mac 近日正式发布&#xff0c;这一新版本不仅全面支持 macOS Sequoia 和 Windows 11 24H2&#xff0c;还在企业版中引入了一个全新的管理门户。新版本针对 Windows、macOS 和 Linux 虚拟机进行了多项改进&#xff0c;其中最引人注目的当属 Parallels …

Python 入门(一、使用 VSCode 开发 Python 环境搭建)

Python 入门第一课 &#xff0c;环境搭建...... by 矜辰所致前言 现在不会 Python &#xff0c;好像不那么合适&#xff0c;咱先不求精通&#xff0c;但也不能不会&#xff0c;话不多说&#xff0c;开干&#xff01; 这是 Python 入门第一课&#xff0c;当然是做好准备工作&a…

计算机毕业设计 校园失物招领网站的设计与实现 Java实战项目 附源码+文档+视频讲解

博主介绍&#xff1a;✌从事软件开发10年之余&#xff0c;专注于Java技术领域、Python人工智能及数据挖掘、小程序项目开发和Android项目开发等。CSDN、掘金、华为云、InfoQ、阿里云等平台优质作者✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精…

嵌入式单片机STM32开发板详细制作过程--01

大家好,今天主要给大家分享一下,单片机开发板的制作过程,原理图的制作与PCB设计,以及电子元器件采购与焊接。 第一:单片机开发板成品展示 板子正面都有各个芯片的丝印与标号,方便焊接元器件的时候,可以参考。(焊接完成之后,成品图如下) 第二:开发板原理图制作 在制…