fix: support folder drag-and-drop upload with directory structure preserved (#2677)

* fix: support folder drag-and-drop upload with directory structure preserved

Drag-dropping a folder onto the knowledge base page was treated as a
single phantom file (size 0, no extension) and failed with "unsupported
file type" on Chrome/Edge, or silently did nothing on Firefox.

Root cause: collectDroppedFiles checked dataTransfer.files first, which
Chrome/Edge populates with non-traversable directory entries for folder
drops. The function never reached the webkitGetAsEntry branch that can
recursively traverse directory contents.

Fix: reverse the priority — try webkitGetAsEntry first to recursively
traverse dropped directories, setting webkitRelativePath on each File to
preserve the folder structure (same format as <input webkitdirectory>).
Fall back to dataTransfer.files only for plain file drags or browsers
without webkitGetAsEntry support.

Additional details:
- readEntries() is called in a loop until empty (batches may be partial)
- Hidden files/directories (segments starting with .) are skipped,
  matching the button-based folder upload behavior
- Top-level dropped files keep webkitRelativePath empty so they upload
  as individual files, not folder uploads
- Object.defineProperty is used with try/catch for Safari compatibility

Closes #2676

* style: switch code comments to Chinese for consistency with existing file

* fix: don't fall back to phantom files after directory drag-drop

Once webkitGetAsEntry returns entries, trust the traversal result even
when it is empty (empty or hidden-only folders). Falling back to
dataTransfer.files reintroduced Chrome/Edge's size-0 directory File.
Also isolate per-item failures and cover the collector with unit tests.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
main
wheatzone 2026-08-13 10:44:16 +08:00 committed by GitHub
parent 0cc3c33530
commit 2384fbae4e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 368 additions and 23 deletions

View File

@ -0,0 +1,227 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { collectDroppedFiles } from './collectDroppedFiles.ts'
function makeFile(name: string, content = 'x'): File {
return new File([content], name)
}
function fileEntry(file: File) {
return {
isFile: true,
isDirectory: false,
name: file.name,
file: (ok: (f: File) => void, _err?: (err?: unknown) => void) => {
queueMicrotask(() => ok(file))
},
}
}
function dirEntry(name: string, children: unknown[], batches?: unknown[][]) {
return {
isFile: false,
isDirectory: true,
name,
createReader: () => {
const pages = batches ?? [children]
let index = 0
return {
readEntries: (ok: (entries: unknown[]) => void) => {
const page = index < pages.length ? pages[index] : []
index += 1
queueMicrotask(() => ok(page as unknown[]))
},
}
},
}
}
function phantomDirFile(name: string): File {
return new File([], name)
}
function makeDragEvent(opts: {
items: Array<{ kind?: string; entry?: unknown; file?: File | null; throwOnEntry?: boolean }>
files?: File[]
}): DragEvent {
const items = opts.items.map((item) => ({
kind: item.kind ?? 'file',
webkitGetAsEntry: item.throwOnEntry
? () => {
throw new Error('entry failed')
}
: item.entry === undefined
? undefined
: () => item.entry,
getAsFile: () => item.file ?? null,
}))
return {
dataTransfer: {
items,
files: opts.files ?? [],
},
} as unknown as DragEvent
}
function relativePath(file: File): string {
return (file as File & { webkitRelativePath?: string }).webkitRelativePath || ''
}
test('folder drop enumerates files and sets webkitRelativePath', async () => {
const nested = makeFile('day-one.md')
const readme = makeFile('README.md')
const event = makeDragEvent({
items: [{
entry: dirEntry('handbook', [
fileEntry(readme),
dirEntry('onboarding', [fileEntry(nested)]),
]),
file: phantomDirFile('handbook'),
}],
files: [phantomDirFile('handbook')],
})
const files = await collectDroppedFiles(event)
assert.deepEqual(
files.map(f => relativePath(f) || f.name).sort(),
['handbook/README.md', 'handbook/onboarding/day-one.md'],
)
})
test('empty folder does not fall back to Chrome phantom directory files', async () => {
const phantom = phantomDirFile('empty')
const event = makeDragEvent({
items: [{ entry: dirEntry('empty', []), file: phantom }],
files: [phantom],
})
const files = await collectDroppedFiles(event)
assert.deepEqual(files, [])
})
test('hidden-only folder does not fall back to phantom directory files', async () => {
const phantom = phantomDirFile('.git')
const event = makeDragEvent({
items: [{
entry: dirEntry('.git', [fileEntry(makeFile('HEAD'))]),
file: phantom,
}],
files: [phantom],
})
const files = await collectDroppedFiles(event)
assert.deepEqual(files, [])
})
test('hidden files and directories inside a folder are skipped', async () => {
const keep = makeFile('notes.md')
const event = makeDragEvent({
items: [{
entry: dirEntry('docs', [
fileEntry(keep),
fileEntry(makeFile('.env')),
dirEntry('.cache', [fileEntry(makeFile('index.json'))]),
]),
}],
files: [phantomDirFile('docs')],
})
const files = await collectDroppedFiles(event)
assert.equal(files.length, 1)
assert.equal(relativePath(files[0]), 'docs/notes.md')
})
test('top-level files keep an empty webkitRelativePath', async () => {
const file = makeFile('report.pdf')
const event = makeDragEvent({
items: [{ entry: fileEntry(file), file }],
files: [file],
})
const files = await collectDroppedFiles(event)
assert.equal(files.length, 1)
assert.equal(files[0], file)
assert.equal(relativePath(files[0]), '')
})
test('falls back to FileList when webkitGetAsEntry is unavailable', async () => {
const file = makeFile('report.pdf')
const event = makeDragEvent({
items: [{ file }],
files: [file],
})
const files = await collectDroppedFiles(event)
assert.deepEqual(files, [file])
})
test('mixed file and folder drops collect both', async () => {
const loose = makeFile('loose.pdf')
const nested = makeFile('inside.md')
const event = makeDragEvent({
items: [
{ entry: fileEntry(loose), file: loose },
{ entry: dirEntry('docs', [fileEntry(nested)]), file: phantomDirFile('docs') },
],
files: [loose, phantomDirFile('docs')],
})
const files = await collectDroppedFiles(event)
assert.equal(files.length, 2)
assert.equal(files[0], loose)
assert.equal(relativePath(files[0]), '')
assert.equal(relativePath(files[1]), 'docs/inside.md')
})
test('a directory whose reader throws does not revive the phantom file', async () => {
const keep = makeFile('keep.md')
const badDir = {
isFile: false,
isDirectory: true,
name: 'bad',
createReader: () => {
throw new Error('no reader')
},
}
const event = makeDragEvent({
items: [
{ entry: badDir, file: phantomDirFile('bad') },
{ entry: fileEntry(keep), file: keep },
],
files: [phantomDirFile('bad'), keep],
})
const files = await collectDroppedFiles(event)
assert.deepEqual(files, [keep])
})
test('a throwing top-level entry does not drop the rest of the batch', async () => {
const keep = makeFile('keep.md')
const event = makeDragEvent({
items: [
{ throwOnEntry: true, file: null },
{ entry: fileEntry(keep), file: keep },
],
files: [keep],
})
const files = await collectDroppedFiles(event)
assert.deepEqual(files, [keep])
})
test('readEntries is drained across partial batches', async () => {
const a = makeFile('a.md')
const b = makeFile('b.md')
const event = makeDragEvent({
items: [{
entry: dirEntry('docs', [], [[fileEntry(a)], [fileEntry(b)]]),
}],
})
const files = await collectDroppedFiles(event)
assert.deepEqual(
files.map(f => relativePath(f)).sort(),
['docs/a.md', 'docs/b.md'],
)
})

View File

@ -0,0 +1,140 @@
// 拖拽文件夹时,Chrome/Edge 会用"假"目录条目(size 0、无扩展名)填充
// dataTransfer.files,而非文件夹内的真实文件。只有 webkitGetAsEntry()
// 能递归遍历拖入的目录,因此必须优先尝试它,仅在入口 API 不可用时才回退
// 到 dataTransfer.files。Firefox 在拖拽文件夹时 dataTransfer.files 为空,
// 同样需要走 entry 遍历路径。
const isHiddenSegment = (segment: string): boolean => segment.startsWith('.')
export const setRelativePath = (file: File, relativePath: string): void => {
try {
Object.defineProperty(file, 'webkitRelativePath', {
value: relativePath,
writable: false,
enumerable: true,
configurable: true,
})
} catch {
// 旧版 Safari 可能拒绝在 File 上 defineProperty,这些文件
// 不会携带相对路径,将以平铺方式上传。
}
}
const readAllDirEntries = (reader: { readEntries: Function }): Promise<any[]> => {
return new Promise((resolve) => {
const collected: any[] = []
const readBatch = () => {
reader.readEntries((entries: any[]) => {
if (!entries || entries.length === 0) {
resolve(collected)
} else {
collected.push(...entries)
readBatch()
}
}, () => resolve(collected))
}
readBatch()
})
}
export const traverseEntry = (entry: any, path: string): Promise<File[]> => {
return new Promise((resolve) => {
try {
if (!entry) {
resolve([])
return
}
if (entry.isFile) {
if (typeof entry.file !== 'function') {
resolve([])
return
}
entry.file((file: File) => {
// 仅对目录内的文件设置 webkitRelativePath,与
// <input webkitdirectory> 行为一致。顶层拖入的文件
// 保持空值,作为普通文件上传。
if (path) {
const relativePath = `${path}/${file.name}`
if (relativePath.split('/').some(isHiddenSegment)) {
resolve([])
return
}
setRelativePath(file, relativePath)
}
resolve([file])
}, () => resolve([]))
} else if (entry.isDirectory) {
const dirPath = path ? `${path}/${entry.name}` : entry.name
// 跳过隐藏目录(.git、.DS_Store 等)
if (dirPath.split('/').some(isHiddenSegment)) {
resolve([])
return
}
if (typeof entry.createReader !== 'function') {
resolve([])
return
}
readAllDirEntries(entry.createReader())
.then(children => Promise.all(
children.map(c => traverseEntry(c, dirPath).catch(() => [] as File[])),
))
.then(results => resolve(results.flat()))
.catch(() => resolve([]))
} else {
resolve([])
}
} catch {
resolve([])
}
})
}
export const collectDroppedFiles = async (event: DragEvent): Promise<File[]> => {
const dataTransfer = event.dataTransfer
const items = dataTransfer?.items ? Array.from(dataTransfer.items) : []
// DataTransfer 仅在 drop 同步阶段保证可用,回退列表必须先拷贝。
const fallbackFiles = dataTransfer?.files ? Array.from(dataTransfer.files) : []
if (items.length === 0) {
return fallbackFiles
}
const fileItems = items.filter(item => item.kind === 'file')
if (fileItems.length === 0) {
return fallbackFiles
}
const pairs = fileItems.map(item => {
try {
return { item, entry: (item as any).webkitGetAsEntry?.() ?? null }
} catch {
return { item, entry: null }
}
})
const usable = pairs.filter(p => p.entry != null)
if (usable.length === 0) {
// 浏览器不支持 webkitGetAsEntry,退回已快照的 FileList。
return fallbackFiles
}
const results = await Promise.all(usable.map(async ({ item, entry }) => {
try {
if (entry.isDirectory) {
return await traverseEntry(entry, '')
}
// 顶层文件用 getAsFile:同步、保留空 webkitRelativePath。
const file = item.getAsFile()
if (file) return [file]
return await traverseEntry(entry, '')
} catch {
if (entry?.isDirectory) return []
const file = item.getAsFile()
return file ? [file] : []
}
}))
// 只要拿到了 FileSystemEntry,就采信遍历结果(包括空数组)。
// 空文件夹 / 全是隐藏文件时若再回退 dataTransfer.files,
// Chrome/Edge 会再次交出 size 0 的幽灵目录项。
return results.flat()
}

View File

@ -32,6 +32,7 @@ import { useChatResourcesStore } from '@/stores/chatResources'
import { getKnowledgeBaseById } from '@/api/knowledge-base/index'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { collectDroppedFiles } from './collectDroppedFiles'
const route = useRoute();
const router = useRouter();
@ -77,29 +78,6 @@ const isChatDropRoute = () => {
return CHAT_DROP_ROUTE_NAMES.has(String(route.name || ''));
}
const collectDroppedFiles = async (event: DragEvent): Promise<File[]> => {
const dataTransferFiles = event.dataTransfer?.files ? Array.from(event.dataTransfer.files) : [];
if (dataTransferFiles.length > 0) {
return dataTransferFiles;
}
const dataTransferItems = event.dataTransfer?.items ? Array.from(event.dataTransfer.items) : [];
if (dataTransferItems.length === 0) {
return [];
}
const files = await Promise.all(dataTransferItems.map(item => new Promise<File | null>((resolve) => {
const fileEntry = (item as any).webkitGetAsEntry?.();
if (fileEntry?.isFile && typeof fileEntry.file === 'function') {
fileEntry.file((file: File) => resolve(file), () => resolve(null));
return;
}
resolve(null);
})));
return files.filter((file): file is File => file instanceof File);
}
// 检查知识库初始化状态
const checkKnowledgeBaseInitialization = async (): Promise<boolean> => {
const currentKbId = getCurrentKbId();