let buffer = ''; // 用于流式缓存
let finalContent = ''; // 累积 markdown 原文
let decoder = new TextDecoder('utf-8');
const requestTask=uni.request({
url:"",
method:"",
data:"",
enableChunked: true, // 重要
})
requestTask.onHeadersReceived(function(res) {})
// 这里监听消息
requestTask.onChunkReceived(function(res) {
const chunk = new Uint8Array(res.data);
// #ifndef MP-WEIXIN
buffer += decoder.decode(chunk, {
stream: true
}); // 累积内容
// #endif
// #ifdef MP-WEIXIN
let text = String.fromCharCode.apply(null, chunk); // 将字节流转为字符串
text = decodeURIComponent(escape(text)); // 处理编码问题
buffer += text; // 累积内容
// #endif
let lines = buffer.split('\n');
buffer = lines.pop(); // 最后一行可能是不完整的,保留到下次
for (let line of lines) {
if (line.startsWith('data:')) {
const jsonStr = line.replace(/^data:\s*/, '');
try {
const parsed = JSON.parse(jsonStr);
const content = parsed.content;
if (Array.isArray(content)) {
finalContent += content.join('');
} else if (typeof content === 'string') {
finalContent += content;
}
// ✅ 用 marked 渲染为 HTML
messages[messageIndex].content = marked(finalContent);
// ✅ 自动滚动到底部
scrollToBottom();
// ✅ 处理结束标志
if (parsed.is_end) {
buffer = '';
finalContent = '';
}
} catch (err) {
console.error('JSON 解析失败:', err, jsonStr);
}
}
}
})
uniapp流式输出
最新推荐文章于 2025-05-16 14:58:10 发布
492

被折叠的 条评论
为什么被折叠?



