Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
88 lines (73 loc) · 2.28 KB
/
Copy pathscript.js
File metadata and controls
88 lines (73 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// 处理与Kimi AI的对话
const chatBox = document.getElementById('chatBox');
const chatInput = document.getElementById('chatInput');
const chatImageUpload = document.getElementById('chatImageUpload');
const sendBtn = document.getElementById('sendBtn');
let currentImageData = null;
// 图片上传处理
chatImageUpload.addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async () => {
// 显示预览
currentImageData = reader.result;
addMessage(`已上传图片: ${file.name}`, 'user');
};
reader.readAsDataURL(file);
});
// 发送消息函数
async function sendMessage() {
const message = chatInput.value.trim();
if (!message && !currentImageData) return;
// 添加用户消息到聊天框
if (message) {
addMessage(message, 'user');
}
// 清空输入框和图片数据
chatInput.value = '';
const imageDataToSend = currentImageData;
currentImageData = null;
try {
// 调用Kimi API获取AI回复
const response = await fetch('/api/new-endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: message,
image: imageDataToSend
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// 添加AI回复到聊天框
addMessage(data.reply, 'ai');
} catch (error) {
console.error('Error:', error);
addMessage('抱歉,发生错误无法获取回复。', 'ai');
}
}
// 添加消息到聊天框
function addMessage(text, sender) {
const messageDiv = document.createElement('div');
messageDiv.className = `mb-4 p-3 rounded-md ${sender === 'user' ? 'bg-primary text-white ml-auto' : 'bg-gray-200 text-gray-800'}`;
messageDiv.style.maxWidth = '70%';
messageDiv.textContent = text;
chatBox.appendChild(messageDiv);
chatBox.scrollTop = chatBox.scrollHeight;
}
// 事件监听
sendBtn.addEventListener('click', sendMessage);
chatInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
// 初始化时自动聚焦输入框
window.addEventListener('load', () => {
chatInput.focus();
});