send(msg)
let obj = {
msg: msg,
uid: this.uid,
}
if (!msg) {
return
}
let time = 600000;
this.isEdit = true;
const requestTask = uni.request({
url: 'https://nd.zhidezhong.com/api/sendMessage',
timeout: time,
responseType: 'text',
method: 'POST',
header: {
'Authorization': 'token',
"Content-Type": "application/json",
},
enableChunked: true, //配置这里,最重要
data: obj,
success: response => {
this.isEdit = false;
console.log(response, '留返回完成')
// 在dom渲染完毕后 使聊天窗口滚动到最后一条消息
this.$nextTick(() => {
this.showLastMsg()
})
},
fail: error => {
console.log(error, '智力开发随叫随到咖啡馆和', time)
}
})
requestTask.onHeadersReceived((res) => {});
requestTask.onChunkReceived((res) => {
console.log(res, '1返回流 ')
// debugger
// let gg = JSON.parse(item.replace('data:', ''));
// debugger
// console.log(uint8Array, '55555啊新春快乐就撒很费劲 ')
const uint8Array = new Uint8Array(res.data);
const decoder = new TextEncoding.TextDecoder("utf-8");
const decodedString = decoder.decode(uint8Array);
// const decoder = new TextEncoding.TextDecoder("utf-8");
// const decodedString = decoder.decode(res.data);
let dataList = decodedString.split('\n\n'),
dataVal = '';
dataList.forEach((item) => {
if (item) {
// console.log(item, '2啊新春快乐就撒很费劲 ')
// const uint8Array = new Uint8Array(item);
// // debugger
// // let gg = JSON.parse(item.replace('data:', ''));
// // debugger
// console.log(uint8Array, '55555啊新春快乐就撒很费劲 ')
let gg = JSON.parse(item.replace('data:', ''));
// console.log(gg, '66666啊新春快乐就撒很费劲 ')
dataVal += gg.content
}
})
if (!this.msgList[this.msgList.length - 1].isAi) {
this.msgList.push({
// 消息创建时间
create_time: Date.now(),
// 标记消息为来自AI机器人
isAi: true,
// 消息内容
content: dataVal,
// 消息是否涉敏标记
})
} else {
let len = this.msgList.length - 1;
let data1 = this.msgList[len];
data1.content = data1.content + dataVal;
this.$set(this.msgList, len, data1)
}
console.log(dataVal, '返回流内容 ')
this.$nextTick(() => {
this.showLastMsg()
})
})
}
// 滚动窗口以显示最新的一条消息
showLastMsg() {
// 等待DOM更新
this.$nextTick(() => {
// 将scrollIntoView属性设置为"last-msg-item",以便滚动窗口到最后一条消息
this.scrollIntoView = "last-msg-item"
// 等待DOM更新,即:滚动完成
this.$nextTick(() => {
// 将scrollIntoView属性设置为空,以便下次设置滚动条位置可被监听
this.scrollIntoView = ""
})
})
},
需要注意的点
- 超时时间 timeout: time,在有的华为手机上,时间设置小了,即便已经开始接收到流的内容了,还是会走到失败里报请求超时;
- const decoder = new TextEncoding.TextDecoder(“utf-8”),微信小程序 真机不支持TextEncoder/TextDecoder对象,需要安装这个;
- 安装方法解决办法:
用npm安装:
pnpm install text-encoding-shim
在页面上引入:
import * as TextEncoding from “text-encoding-shim”;
使用方法:
new TextEncoding.TextDecoder(“utf-8”).decode()
const decoder = new TextEncoding.TextDecoder(“utf-8”);
const str = decoder.decode(new Uint8Array(Uint8Array数据流));