Vue前端项目处理AI流式传输填充数据
'stream':(仅限Node.js环境):服务器响应会被处理成一个Stream对象,可以用来处理大文件或者边下载边处理的场景。'blob':(仅限浏览器环境):服务器响应会被解析成一个Blob对象,适合文件处理,尤其是大文件或需要存储到本地的情况。'arraybuffer':服务器响应会被解析成一个ArrayBuffer对象,适合处理二进制数据,如文件下载。'json' (默认):服务器响应会
<template>
<el-form-item label="商品简介:" prop="intro">
<el-input
class="from-ipt-width"
v-model.trim="formValidate.intro"
type="textarea"
maxlength="100"
:rows="3"
placeholder="请输入商品简介"
show-word-limit
:disabled="isDisabled"
/>
<div class="marketingBox">
<div class="from-tips">通过公众号分享商品详情,会展示此简介信息</div>
<el-button
@click="fetchStreamingJSON"
:loading="isGeneratingAI"
:disabled="isGeneratingAI"
>
{{ isGeneratingAI ? 'AI生成中...' : 'AI营销填充' }}
</el-button>
</div>
</el-form-item>
</template>
methods: {
async fetchStreamingJSON() {
try {
this.isGeneratingAI = true;
this.$set(this.formValidate, 'intro', '');
this.$message.info('正在生成AI营销文案,请稍候...');
// 使用原生的 Fetch API,因为需要用到stream的responseType,在axios中,浏览器不支持stream,只有Node.js才支持
const response = await fetch('http://192.168.10.117:9001/api/goods/copywriting_generate', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + getToken(),
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: this.formValidate.name,
stream: true
})
});
console.log('response',response);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
if (!response.body) {
throw new Error('ReadableStream not supported in this browser.');
}
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) {
// 处理最后的数据
if (buffer.trim()) {
await this.processBuffer(buffer);
}
this.$message.success('AI营销文案生成完成!');
break;
}
// 实时处理数据
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.trim()) {
await this.processLine(line);
}
}
}
} catch (error) {
console.error('生成AI营销文案时出错:', error);
this.$message.error('生成AI营销文案失败,请重试');
} finally {
this.isGeneratingAI = false;
}
},
async processLine(line) {
try {
const jsonData = JSON.parse(line);
console.log('实时接收到数据:', jsonData);
if (jsonData.data && typeof jsonData.data === 'string' && jsonData.data !== '') {
// 实时添加到intro中
this.$set(this.formValidate, 'intro', this.formValidate.intro + jsonData.data);
this.$forceUpdate();
}
} catch (e) {
console.warn('解析JSON出错:', e, '原始数据:', line);
}
},
}
需要了解到axios的responseType配置项可以接受多种值,用于指定服务器响应的数据类型。
配置项:
'json' (默认):服务器响应会被解析成JavaScript对象。
'arraybuffer':服务器响应会被解析成一个ArrayBuffer对象,适合处理二进制数据,如文件下载。
'text':服务器响应会被解析成字符串。
'document':服务器响应会被解析成一个HTML文档。
'stream':(仅限Node.js环境):服务器响应会被处理成一个Stream对象,可以用来处理大文件或者边下载边处理的场景。
'blob':(仅限浏览器环境):服务器响应会被解析成一个Blob对象,适合文件处理,尤其是大文件或需要存储到本地的情况
// Axios 的工作方式:
1. 发送请求
2. 等待服务器完全响应
3. 将所有数据收集到 response.data
4. 然后才返回 response 对象
// Fetch API 的工作方式:
1. 发送请求
2. 立即返回 response 对象(包含 body ReadableStream)
3. 你可以实时读取数据流
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)