kongdeqiang
2026-10-09 f55d84f8479f35f780c535d2d4f4836727363255
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
<template>
  <div class="file-upload">
    <div
      class="drop-zone"
      :class="{ dragging: isDragging, uploading }"
      @dragover.prevent="isDragging = true"
      @dragleave.prevent="isDragging = false"
      @drop.prevent="handleDrop"
      @click="pickFile"
    >
      <input
        ref="fileInputRef"
        type="file"
        class="hidden-input"
        multiple
        :accept="acceptAttr"
        @change="handleSelect"
      />
      <div class="drop-icon">↑</div>
      <div class="drop-title">
        {{ uploading ? statusText : '拖拽文件到此处,或点击选择' }}
      </div>
      <div class="drop-hint">
        支持 {{ allowedExtensions.join(' / ') }},单个文件不超过 {{ maxSizeMb }}MB
      </div>
      <n-progress
        v-if="uploading"
        type="line"
        :percentage="progress"
        :show-indicator="false"
        class="drop-progress"
      />
    </div>
 
    <!-- 上传前选好分类,上传后自动归类,省去传完再一个个指定 -->
    <div v-if="showCategory" class="upload-category">
      <CategoryPicker
        v-model:value="categoryId"
        :allow-global="allowGlobalCategory"
        :disabled="uploading"
        placeholder="选择分类(可不选)"
        @created="$emit('category-created', $event)"
      />
    </div>
 
    <!--
      自动向量化开关:默认开启。
      关掉它只有在「批量上传几百个文件、想自己控制入库时机」时才有意义,
      所以放在次要位置,不抢视觉焦点。
    -->
    <label class="auto-ingest">
      <n-switch v-model:value="autoIngest" size="small" :disabled="uploading" />
      <span class="auto-ingest-label">
        上传后立即向量化
        <span class="auto-ingest-hint">(关闭后需手动点「向量化」才能被检索到)</span>
      </span>
    </label>
 
    <div v-if="error" class="upload-error">{{ error }}</div>
  </div>
</template>
 
<script setup>
import { computed, ref } from 'vue'
import { NProgress, NSwitch, useMessage } from 'naive-ui'
import { uploadFile } from '@/api/fileApi'
import CategoryPicker from './CategoryPicker.vue'
 
const props = defineProps({
  /** 绑定的会话 id;为空表示上传为公共知识库文件 */
  chatId: { type: Number, default: null },
  /** 单文件大小上限(MB) */
  maxSizeMb: { type: Number, default: 50 },
  /** 是否显示分类选择器 */
  showCategory: { type: Boolean, default: true },
  /** 是否允许创建全局分类(仅管理员页面传 true) */
  allowGlobalCategory: { type: Boolean, default: false }
})
 
const emit = defineEmits(['uploaded', 'category-created'])
 
const message = useMessage()
const fileInputRef = ref(null)
const isDragging = ref(false)
const uploading = ref(false)
const progress = ref(0)
const error = ref('')
// 默认开启:未入库的文件对检索无效,「上传完却搜不到」是最容易让人困惑的场景
const autoIngest = ref(true)
/** 选中的分类;null 表示不归类 */
const categoryId = ref(null)
/** 当前阶段文案:上传字节 vs 向量化(后者耗时通常远大于前者) */
const statusText = ref('')
 
/**
 * 上传阶段的进度映射。
 *
 * 上传字节只占整个流程的一小部分,向量化(解析 + embedding + 写向量库)
 * 才是主要耗时。若把总进度直接按上传百分比显示,会卡在 100% 不动,
 * 用户以为卡死了。因此把上传映射到 0-40%,剩下的留给向量化阶段。
 */
const uploadPhasePercent = (rawPercent) => Math.round(rawPercent * 0.4)
 
// 与后端 webui.storage.allowed-extensions 保持一致。
// 前端限制只是体验优化,真正的安全边界在后端。
const allowedExtensions = [
  'txt', 'md', 'markdown', 'pdf', 'docx', 'csv', 'json', 'log', 'html',
  // 图片会走 OCR 提取文字后入库
  'png', 'jpg', 'jpeg', 'webp', 'bmp', 'gif', 'tif', 'tiff'
]
 
const acceptAttr = computed(() =>
  allowedExtensions.map((ext) => `.${ext}`).join(',')
)
 
function pickFile() {
  if (uploading.value) return
  fileInputRef.value?.click()
}
 
function handleSelect(event) {
  const files = Array.from(event.target.files || [])
  // 清空 value,否则选择同一个文件不会再次触发 change 事件
  event.target.value = ''
  uploadFiles(files)
}
 
function handleDrop(event) {
  isDragging.value = false
  if (uploading.value) return
  uploadFiles(Array.from(event.dataTransfer?.files || []))
}
 
async function uploadFiles(files) {
  if (files.length === 0) return
 
  error.value = ''
  uploading.value = true
  progress.value = 0
 
  const succeeded = []
 
  try {
    for (let index = 0; index < files.length; index += 1) {
      const file = files[index]
 
      // 客户端预检:给出即时反馈,不必等一个来回
      const extension = file.name.split('.').pop()?.toLowerCase() || ''
      if (!allowedExtensions.includes(extension)) {
        message.error(`${file.name}:不支持的文件类型 .${extension}`)
        continue
      }
      if (file.size > props.maxSizeMb * 1024 * 1024) {
        message.error(`${file.name}:超过 ${props.maxSizeMb}MB 限制`)
        continue
      }
 
      try {
        const base = index / files.length
        const slice = 1 / files.length
 
        statusText.value = `上传中 ${file.name}`
        progress.value = Math.round(base * 100)
 
        const result = await uploadFile(
          file,
          props.chatId,
          (percent) => {
            // 上传只占该文件进度的前 40%,剩余留给向量化
            progress.value = Math.round((base + (uploadPhasePercent(percent) / 100) * slice) * 100)
          },
          autoIngest.value,
          categoryId.value
        )
 
        // 上传已返回,若开启了自动向量化,后端此时已经做完入库
        progress.value = Math.round((base + slice) * 100)
 
        if (autoIngest.value && result && result.ingested === false && result.ingestMessage) {
          // 文件存下来了,但向量化失败 —— 明确告知,不静默吞掉
          message.warning(`${file.name} 已上传,但${result.ingestMessage}`)
        } else if (autoIngest.value && result && result.chunkCount) {
          message.success(`${file.name} 已入库 ${result.chunkCount} 个片段`)
        }
        succeeded.push(result)
      } catch (uploadError) {
        message.error(`${file.name}:${uploadError.message || '上传失败'}`)
      }
    }
 
    if (succeeded.length > 0) {
      const ingested = succeeded.filter((f) => f && f.ingested).length
      if (autoIngest.value) {
        message.success(`成功上传 ${succeeded.length} 个文件,其中 ${ingested} 个已入库可检索`)
      } else {
        // 关掉自动向量化时必须说清楚后果,否则用户会以为已经能用了
        message.info(`成功上传 ${succeeded.length} 个文件,尚未向量化,需点「向量化」后才能被检索到`)
      }
      emit('uploaded', succeeded)
    }
  } finally {
    uploading.value = false
    progress.value = 0
    statusText.value = ''
  }
}
</script>
 
<style scoped>
.hidden-input {
  display: none;
}
 
.drop-zone {
  border: 1.5px dashed #d1d5db;
  border-radius: 10px;
  padding: 22px 16px;
  text-align: center;
  cursor: pointer;
  background: #fafafa;
  transition: border-color 0.15s ease, background 0.15s ease;
}
 
.drop-zone:hover {
  border-color: #9ca3af;
  background: #f5f5f5;
}
 
.drop-zone.dragging {
  border-color: #4b5563;
  background: #eef2f7;
}
 
.drop-zone.uploading {
  cursor: progress;
}
 
.drop-icon {
  font-size: 20px;
  color: var(--text-secondary);
  margin-bottom: 8px;
}
 
.drop-title {
  font-size: 13.5px;
  color: var(--text-primary);
  font-weight: 500;
}
 
.drop-hint {
  font-size: 12px;
  color: var(--text-muted);
  margin-top: 6px;
  line-height: 1.6;
}
 
.drop-progress {
  margin-top: 12px;
}
 
.upload-category {
  margin-top: 10px;
}
 
.auto-ingest {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-top: 10px;
  cursor: pointer;
  user-select: none;
}
 
.auto-ingest-label {
  font-size: 12.5px;
  color: var(--text-secondary);
  line-height: 1.5;
}
 
.auto-ingest-hint {
  color: var(--text-muted);
}
 
.upload-error {
  margin-top: 8px;
  font-size: 12.5px;
  color: #dc2626;
}
</style>