网页,postman ,接口都表现正常,开启 enableChunked: true, 后就乱码,求解
let task = wx.request({
url: 'https://xxx/api/chat/generate',
enableChunked: true,
method: "GET",
})
task.onChunkReceived((buffer) => {
// const decoder = new TextDecoder("utf-8");
// const str = decoder.decode(new Uint8Array(buffer.data))
const arrayBuffer = buffer.data;
const uint8Array = new Uint8Array(arrayBuffer);
let text = String.fromCharCode.apply(null, uint8Array);
console.log('onChunkReceived',text)
})
chrome表现
postman
后台接口
乱码
请具体描述问题出现的流程,并提供能复现问题的简单代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)。
text = decodeURIComponent(escape(text));
@OptIn(BetaOpenAI::class)
@GetMapping("generate", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
fun chat(): Flow<String> {
return chatService.chat().map { chat ->
var content = ""
chat.choices.forEach { chatChunk ->
chatChunk.delta?.content?.apply {
content += this
}
}
// print("content == $content")
Base64.getEncoder().encodeToString(content.toByteArray(Charsets.UTF_8))
}
}
前端使用base64界面后就可以了
const arrayBuffer = buffer.data;
const uint8Array = new Uint8Array(arrayBuffer);
let oText = String.fromCharCode.apply(null, uint8Array)
let text = oText.replaceAll("data:", "")
let res = ""
if (text.length > 0) {
res = Base64.decode(text)
}
all += res
this.setData({
info: all
})
开发者工具的问题,真机不会乱码
var requestTask = wx.request({
url:'http://**/chat',
data: {
message:'10字关于冬的作文'
},
method:'POST',
responseType:'arraybuffer',
enableChunked:true
})
requestTask.onChunkReceived(value => {
console.log(value)
let res = new TextDecoder().decode(value.data);
console.log(res);
})