allow user to upload attachment for mobile chat page

This commit is contained in:
RockYang
2025-09-08 08:43:32 +08:00
parent 18961d3c26
commit 8b2cf90aab
10 changed files with 357 additions and 114 deletions

View File

@@ -244,7 +244,16 @@ func (h *ModerationHandler) UpdateModeration(c *gin.Context) {
return
}
err := h.DB.Where("name", types.ConfigKeyModeration).FirstOrCreate(&model.Config{Name: types.ConfigKeyModeration, Value: utils.JsonEncode(data)}).Error
var config model.Config
err := h.DB.Where("name", types.ConfigKeyModeration).First(&config).Error
if err != nil {
config.Name = types.ConfigKeyModeration
config.Value = utils.JsonEncode(data)
err = h.DB.Create(&config).Error
} else {
config.Value = utils.JsonEncode(data)
err = h.DB.Updates(&config).Error
}
if err != nil {
resp.ERROR(c, err.Error())
return

View File

@@ -345,6 +345,7 @@ func (h *ChatHandler) sendMessage(ctx context.Context, input ChatInput, c *gin.C
continue
} else {
fileContents = append(fileContents, fmt.Sprintf("%s 文件内容:%s", file.Name, content))
logger.Debugf("fileContents: %s", fileContents)
}
}
}

View File

@@ -49,6 +49,77 @@
}
}
}
// .file-preview-list {
// display: flex;
// flex-wrap: wrap;
// padding: 6px 10px 0 10px;
// gap: 8px;
// .file-preview-item {
// position: relative;
// display: inline-flex;
// align-items: center;
// border: 1px solid #e8e8e8;
// background: var(--van-cell-background);
// border-radius: 8px;
// padding: 6px 26px 6px 6px;
// overflow: hidden;
// .thumb {
// width: 56px;
// height: 56px;
// border-radius: 6px;
// overflow: hidden;
// .img {
// width: 56px;
// height: 56px;
// }
// .size {
// position: absolute;
// left: 6px;
// bottom: 6px;
// background: rgba(0, 0, 0, 0.5);
// color: #fff;
// font-size: 10px;
// padding: 1px 4px;
// border-radius: 3px;
// }
// }
// .doc {
// display: inline-flex;
// align-items: center;
// gap: 6px;
// max-width: 220px;
// .icon {
// width: 24px;
// height: 24px;
// }
// .name {
// white-space: nowrap;
// text-overflow: ellipsis;
// overflow: hidden;
// max-width: 180px;
// }
// .size {
// color: #8c8c8c;
// font-size: 12px;
// margin-left: 6px;
// }
// }
// .remove {
// position: absolute;
// right: 6px;
// top: 6px;
// font-size: 14px;
// color: #999;
// }
// }
// }
}
}

View File

@@ -81,6 +81,7 @@ const removeFile = (file) => {
border: 1px solid #e3e3e3;
padding: 6px;
margin-right: 10px;
max-height: 54px;
.icon {
.el-image {
@@ -91,10 +92,10 @@ const removeFile = (file) => {
.body {
margin-left: 5px;
font-size: 14px;
font-size: 12px;
.title {
line-height: 24px;
// line-height: 20px;
color: #0d0d0d;
}

View File

@@ -1,12 +1,17 @@
<template>
<div class="mobile-message-prompt">
<div class="chat-item">
<div ref="contentRef" :data-clipboard-text="content" class="content" v-html="content"></div>
<div class="triangle"></div>
<div class="mb-2">
<MobileFileList :files="files" direction="col" />
</div>
<div class="flex justify-end">
<div class="chat-item">
<div ref="contentRef" :data-clipboard-text="content" class="content" v-html="content"></div>
<div class="triangle"></div>
</div>
<div class="chat-icon">
<van-image :src="icon" />
<div class="chat-icon">
<van-image :src="icon" />
</div>
</div>
</div>
</template>
@@ -15,6 +20,7 @@
import Clipboard from 'clipboard'
import { showNotify } from 'vant'
import { onMounted, ref } from 'vue'
import MobileFileList from '@/components/mobile/MobileFileList.vue'
// eslint-disable-next-line no-unused-vars,no-undef
const props = defineProps({
@@ -34,6 +40,7 @@ const contentRef = ref(null)
const content = computed(() => {
return props.content.text
})
const files = computed(() => props.content.files || [])
onMounted(() => {
const clipboard = new Clipboard(contentRef.value)
clipboard.on('success', () => {
@@ -47,9 +54,6 @@ onMounted(() => {
<style lang="scss">
.mobile-message-prompt {
display: flex;
justify-content: flex-end;
.chat-icon {
margin-left: 5px;
@@ -67,6 +71,51 @@ onMounted(() => {
padding: 0 5px 0 0;
overflow: hidden;
.file-list {
margin: 0 0 6px 0;
.image {
.img {
width: 120px;
height: 120px;
border-radius: 6px;
margin-bottom: 6px;
}
}
.doc {
display: flex;
align-items: center;
gap: 6px;
background: #ffffff;
border: 1px solid #e8e8e8;
border-radius: 8px;
padding: 6px 8px;
margin-bottom: 6px;
.icon {
width: 24px;
height: 24px;
}
.meta {
display: flex;
align-items: center;
gap: 6px;
.name {
max-width: 180px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.size {
color: #8c8c8c;
font-size: 12px;
}
}
}
}
.triangle {
width: 0;
height: 0;

View File

@@ -7,12 +7,7 @@
<div class="chat-item">
<div class="triangle"></div>
<div class="content-box" ref="contentRef">
<div
v-if="content"
:data-clipboard-text="orgContent"
class="content content-mobile"
v-html="content"
></div>
<div v-if="content" class="content content-mobile" v-html="content"></div>
<div v-else-if="error">
<div class="content content-mobile !text-red-500">{{ error }}</div>
</div>
@@ -32,15 +27,31 @@
>
{{ isGenerating ? '生成中...' : '重新生成' }}
</van-button>
<van-button
size="mini"
type="success"
:data-clipboard-text="orgContent"
class="copy-answer"
plain
>
复制回答
</van-button>
</div>
</div>
</div>
</template>
<script setup>
import { computed, onMounted, ref } from 'vue'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { showImagePreview } from 'vant'
import Thinking from '../Thinking.vue'
import hl from 'highlight.js'
import MarkdownIt from 'markdown-it'
import emoji from 'markdown-it-emoji'
import mathjaxPlugin from 'markdown-it-mathjax3'
import { processContent } from '@/utils/libs'
import Clipboard from 'clipboard'
import { showNotify } from 'vant'
const props = defineProps({
content: {
@@ -77,9 +88,37 @@ const props = defineProps({
})
const emits = defineEmits(['regenerate'])
const md = new MarkdownIt({
breaks: true,
html: true,
linkify: true,
typographer: true,
highlight: function (str, lang) {
const codeIndex = parseInt(Date.now()) + Math.floor(Math.random() * 10000000)
// 显示复制代码按钮
const copyBtn = `<span class="copy-code-mobile" data-clipboard-action="copy" data-clipboard-target="#copy-target-${codeIndex}">复制</span>
<textarea style="position: absolute;top: -9999px;left: -9999px;z-index: -9999;" id="copy-target-${codeIndex}">${str.replace(
/<\/textarea>/g,
'&lt;/textarea>'
)}</textarea>`
if (lang && hl.getLanguage(lang)) {
const langHtml = `<span class="lang-name">${lang}</span>`
// 处理代码高亮
const preCode = hl.highlight(str, { language: lang }).value
// 将代码包裹在 pre 中
return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code>${copyBtn} ${langHtml}</pre>`
}
// 处理代码高亮
const preCode = md.utils.escapeHtml(str)
// 将代码包裹在 pre 中
return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code>${copyBtn}</pre>`
},
})
md.use(mathjaxPlugin)
md.use(emoji)
const content = computed(() => {
return props.content.text
return md.render(processContent(props.content.text))
})
const contentRef = ref(null)
@@ -89,6 +128,7 @@ const handleRegenerate = () => {
emits('regenerate', props.messageId)
}
const clipboard = ref(null)
onMounted(() => {
const imgs = contentRef.value.querySelectorAll('img')
for (let i = 0; i < imgs.length; i++) {
@@ -100,6 +140,18 @@ onMounted(() => {
showImagePreview([imgs[i].src])
})
}
clipboard.value = new Clipboard('.copy-answer,.copy-code-mobile')
clipboard.value.on('success', () => {
showNotify({ type: 'success', message: '复制成功', duration: 1000 })
})
clipboard.value.on('error', () => {
showNotify({ type: 'danger', message: '复制失败', duration: 2000 })
})
})
onUnmounted(() => {
clipboard.value.destroy()
})
</script>

View File

@@ -0,0 +1,68 @@
<template>
<div v-if="items.length" :class="[containerClass, direction === 'col' ? '!items-end' : '']">
<div
v-for="(f, idx) in items"
:key="f.url || idx"
:class="[
'relative inline-flex items-center border border-gray-200 rounded-xl bg-white dark:bg-[#2b2b2b] dark:border-gray-700',
isImage(f.ext) ? 'p-0' : 'p-2',
]"
>
<div v-if="isImage(f.ext)" class="relative w-[56px] h-[56px] overflow-hidden rounded-lg">
<img :src="f.url" alt="img" class="w-full h-full object-cover" />
</div>
<div v-else :class="['flex items-center', direction === 'col' ? 'w-full' : 'max-w-[240px]']">
<img :src="GetFileIcon(f.ext)" class="w-10 h-10 mr-2" />
<div class="min-w-0 flex flex-col items-center gap-1 text-sm">
<a
:href="f.url"
target="_blank"
class="truncate block"
:class="direction === 'col' ? 'text-base max-w-full' : 'max-w-[180px]'"
>{{ f.name }}</a
>
<div class="text-xs flex w-full justify-start text-gray-500">
{{ extUpper(f.ext) }} · {{ FormatFileSize(f.size || 0) }}
</div>
</div>
</div>
<button
v-if="removable"
class="absolute -right-2 -top-2 w-5 h-5 rounded-full bg-rose-600 text-white flex items-center justify-center text-[10px]"
@click="onRemove(f, idx)"
>
×
</button>
</div>
</div>
</template>
<script setup>
import { FormatFileSize, GetFileIcon } from '@/store/system'
import { isImage } from '@/utils/libs'
const props = defineProps({
files: {
type: Array,
default: () => [],
},
removable: {
type: Boolean,
default: false,
},
direction: {
type: String,
default: 'row',
},
})
const emits = defineEmits(['remove'])
const items = computed(() => props.files || [])
const onRemove = (f, idx) => emits('remove', { file: f, index: idx })
const direction = computed(() => props.direction)
const containerClass = computed(() =>
props.direction === 'col' ? 'flex flex-col gap-2' : 'flex flex-wrap gap-2 px-2 pt-2'
)
const extUpper = (ext) => (ext || '').replace('.', '').toUpperCase() || 'FILE'
</script>
<style scoped></style>

View File

@@ -384,7 +384,7 @@ import FileSelect from '@/components/FileSelect.vue'
import Welcome from '@/components/Welcome.vue'
import { checkSession, getClientId, getSystemInfo } from '@/store/cache'
import { useSharedStore } from '@/store/sharedata'
import { closeLoading, showLoading, showMessageError } from '@/utils/dialog'
import { closeLoading, showLoading, showMessageError, showMessageInfo } from '@/utils/dialog'
import { httpGet, httpPost } from '@/utils/http'
import { isMobile, randString, removeArrayItem, UUID } from '@/utils/libs'
import {
@@ -1162,7 +1162,7 @@ const stopGenerate = function () {
isGenerating.value = false
httpGet('/api/chat/stop?session_id=' + getClientId())
.then(() => {
console.log('会话已中断')
showMessageInfo('会话已中断')
})
.catch((e) => {
showMessageError('中断对话失败:' + e.message)

View File

@@ -104,8 +104,12 @@ checkSession()
.then((user) => {
loginUser.value = user
isLogin.value = true
})
.finally(() => {
loading.value = false
finished.value = true
// 加载角色列表
httpGet(`/api/app/list/user`)
httpGet(`/api/app/list`)
.then((res) => {
if (res.data) {
const items = res.data
@@ -139,44 +143,6 @@ checkSession()
showFailToast('加载模型失败: ' + e.message)
})
})
.catch(() => {
loading.value = false
finished.value = true
// 加载角色列表
httpGet('/api/app/list/user')
.then((res) => {
if (res.data) {
const items = res.data
for (let i = 0; i < items.length; i++) {
// console.log(items[i])
roles.value.push({
text: items[i].name,
value: items[i].id,
icon: items[i].icon,
helloMsg: items[i].hello_msg,
})
}
}
})
.catch(() => {
showFailToast('加载聊天角色失败')
})
// 加载模型
httpGet('/api/model/list')
.then((res) => {
if (res.data) {
const items = res.data
for (let i = 0; i < items.length; i++) {
models.value.push({ text: items[i].name, value: items[i].id })
}
}
})
.catch((e) => {
showFailToast('加载模型失败: ' + e.message)
})
})
const onLoad = () => {
checkSession()

View File

@@ -58,8 +58,23 @@
center
clearable
placeholder="输入你的问题"
type="textarea"
rows="1"
:autosize="{ maxHeight: 100, minHeight: 20 }"
show-word-limit
@keyup.enter="sendMessage"
>
<template #left-icon>
<van-uploader
:after-read="afterRead"
:max-count="6"
:multiple="true"
:preview-image="false"
accept=".doc,.docx,.jpg,.jpeg,.png,.gif,.bmp,.webp,.svg,.ico,.xls,.xlsx,.ppt,.pptx,.pdf,.mp4,.mp3,.txt,.md,.csv,.html"
>
<van-icon name="photo" />
</van-uploader>
</template>
<template #button>
<van-button size="small" type="primary" v-if="!isGenerating" @click="sendMessage"
>发送</van-button
@@ -73,6 +88,7 @@
</van-field>
</van-cell-group>
</van-sticky>
<MobileFileList :files="files" removable @remove="onRemovePreview" />
</div>
</div>
</div>
@@ -102,19 +118,17 @@ import ChatReply from '@/components/mobile/ChatReply.vue'
import { checkSession } from '@/store/cache'
import { getUserToken } from '@/store/session'
import { useSharedStore } from '@/store/sharedata'
import { showMessageError } from '@/utils/dialog'
import { httpGet } from '@/utils/http'
import { showMessageError, showLoading, closeLoading } from '@/utils/dialog'
import { httpGet, httpPost } from '@/utils/http'
import MobileFileList from '@/components/mobile/MobileFileList.vue'
import { processContent, randString, renderInputText, UUID } from '@/utils/libs'
import { fetchEventSource } from '@microsoft/fetch-event-source'
// 移除 Clipboard.js 相关内容
import hl from 'highlight.js'
import 'highlight.js/styles/a11y-dark.css'
import MarkdownIt from 'markdown-it'
import emoji from 'markdown-it-emoji'
import mathjaxPlugin from 'markdown-it-mathjax3'
import { showImagePreview, showNotify, showToast } from 'vant'
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { getClientId } from '@/store/cache'
const winHeight = ref(0)
const navBarRef = ref(null)
@@ -205,35 +219,7 @@ const finished = ref(false)
const error = ref(false)
const store = useSharedStore()
const url = ref(location.protocol + '//' + location.host + '/chat/export?chat_id=' + chatId.value)
const md = new MarkdownIt({
breaks: true,
html: true,
linkify: true,
typographer: true,
highlight: function (str, lang) {
const codeIndex = parseInt(Date.now()) + Math.floor(Math.random() * 10000000)
// 显示复制代码按钮
const copyBtn = `<span class="copy-code-mobile" data-clipboard-action="copy" data-clipboard-target="#copy-target-${codeIndex}">复制</span>
<textarea style="position: absolute;top: -9999px;left: -9999px;z-index: -9999;" id="copy-target-${codeIndex}">${str.replace(
/<\/textarea>/g,
'&lt;/textarea>'
)}</textarea>`
if (lang && hl.getLanguage(lang)) {
const langHtml = `<span class="lang-name">${lang}</span>`
// 处理代码高亮
const preCode = hl.highlight(lang, str, true).value
// 将代码包裹在 pre 中
return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code>${copyBtn} ${langHtml}</pre>`
}
// 处理代码高亮
const preCode = md.utils.escapeHtml(str)
// 将代码包裹在 pre 中
return `<pre class="code-container"><code class="language-${lang} hljs">${preCode}</code>${copyBtn}</pre>`
},
})
md.use(mathjaxPlugin)
md.use(emoji)
onMounted(() => {
winHeight.value =
window.innerHeight - navBarRef.value.$el.offsetHeight - bottomBarRef.value.$el.offsetHeight - 70
@@ -284,17 +270,10 @@ const loadChatHistory = () => {
}
data[i].showAction = true
data[i].orgContent = data[i].content.text
data[i].content.text = md.render(processContent(data[i].content.text))
chatData.value.push(data[i])
}
nextTick(() => {
hl.configure({ ignoreUnescapedHTML: true })
const blocks = document.querySelector('#message-list-box').querySelectorAll('pre code')
blocks.forEach((block) => {
hl.highlightElement(block)
})
scrollListBox()
})
})
@@ -325,6 +304,23 @@ const scrollListBox = () => {
.scrollTo(0, document.getElementById('message-list-box').scrollHeight + 46)
}
// 滚动到输入区域,确保预览文件可见
const scrollToBottomBar = () => {
try {
// 优先让底部输入区域进入视野
bottomBarRef.value &&
bottomBarRef.value.$el &&
bottomBarRef.value.$el.scrollIntoView({
behavior: 'smooth',
block: 'end',
})
} catch (e) {}
// 再兜底滚动到页面底部
try {
window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'smooth' })
} catch (e) {}
}
// 发送 SSE 请求
const sendSSERequest = async (message) => {
try {
@@ -378,15 +374,9 @@ const sendSSERequest = async (message) => {
lineBuffer.value += data.body
const reply = chatData.value[chatData.value.length - 1]
reply['orgContent'] = lineBuffer.value
reply['content']['text'] = md.render(processContent(lineBuffer.value))
reply['content']['text'] = lineBuffer.value
nextTick(() => {
hl.configure({ ignoreUnescapedHTML: true })
const lines = document.querySelectorAll('.message-line')
const blocks = lines[lines.length - 1].querySelectorAll('pre code')
blocks.forEach((block) => {
hl.highlightElement(block)
})
scrollListBox()
const items = document.querySelectorAll('.message-line')
@@ -419,7 +409,7 @@ const sendSSERequest = async (message) => {
onerror(err) {
console.error('SSE Error:', err)
try {
abortController.value && abortController.value.abort()
abortController && abortController.abort()
} catch (e) {
console.error('AbortController abort error:', e)
}
@@ -433,7 +423,7 @@ const sendSSERequest = async (message) => {
})
} catch (error) {
try {
abortController.value && abortController.value.abort()
abortController && abortController.abort()
} catch (e) {
console.error('AbortController abort error:', e)
}
@@ -460,7 +450,7 @@ const sendMessage = () => {
type: 'prompt',
id: randString(32),
icon: loginUser.value.avatar,
content: { text: renderInputText(prompt.value) },
content: { text: renderInputText(prompt.value), files: files.value },
created_at: new Date().getTime(),
})
// 添加空回复消息
@@ -473,6 +463,7 @@ const sendMessage = () => {
icon: _role['icon'],
content: {
text: '',
files: [],
},
})
@@ -488,21 +479,23 @@ const sendMessage = () => {
chat_id: chatId.value,
prompt: prompt.value,
stream: stream.value,
files: files.value,
})
previousText.value = prompt.value
prompt.value = ''
files.value = []
return true
}
// 停止生成
const stopGenerate = function () {
if (abortController.value) {
abortController.value.abort()
if (abortController) {
abortController.abort()
isGenerating.value = false
httpGet('/api/chat/stop?session_id=' + getClientId())
.then(() => {
console.log('会话已中断')
showToast('会话已中断')
})
.catch((e) => {
showMessageError('中断对话失败:' + e.message)
@@ -551,6 +544,7 @@ const handleRegenerate = (messageId) => {
last_msg_id: messageId,
prompt: userPrompt.content.text,
stream: stream.value,
files: [],
})
}
@@ -594,6 +588,38 @@ const copyShareUrl = async () => {
showNotify({ type: 'danger', message: '复制失败', duration: 2000 })
}
}
// 文件上传与管理
const files = ref([])
const isHttpUrl = (url) => url.startsWith('http://') || url.startsWith('https://')
const toAbsUrl = (url) => (isHttpUrl(url) ? url : location.protocol + '//' + location.host + url)
const afterRead = async (fileItem) => {
showLoading('文件上传中...')
try {
const file = Array.isArray(fileItem) ? fileItem[0].file : fileItem.file || fileItem
const formData = new FormData()
formData.append('file', file, file.name)
const res = await httpPost('/api/upload', formData)
const f = res.data || {}
f.url = toAbsUrl(f.url || '')
files.value = [f, ...files.value]
// 确保上传后文件预览立即可见
nextTick(() => {
scrollToBottomBar()
})
} catch (e) {
showNotify({ type: 'danger', message: '文件上传失败:' + (e.message || '网络错误') })
} finally {
closeLoading()
}
}
const removeFile = (f, idx) => {
files.value.splice(idx, 1)
}
const onRemovePreview = ({ file, index }) => {
files.value.splice(index, 1)
}
</script>
<style lang="scss" scoped>