uniapp流式输出

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);
					}
				}
			}
})
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值