-
Notifications
You must be signed in to change notification settings - Fork 285
fix(uploader): 处理非图片文件类型问题 #3343
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix(uploader): 处理非图片文件类型问题 #3343
Conversation
Walkthrough将文件加入时立即把 per-file 信息追加到 Changes
Sequence Diagram(s)sequenceDiagram
participant User as 用户
participant Uploader as Uploader 组件
participant FR as FileReader
participant UI as 可视列表
User->>Uploader: 选中文件并触发 addFile
Uploader->>Uploader: 创建 per-file info 并 append 到 fileListRef.current
alt preview 为 true(不再限定图片)
Uploader->>FR: 调用 FileReader.readAsDataURL(file)
FR-->>Uploader: onload 返回 dataURL
Uploader->>Uploader: 在 fileListRef.current 中按 uid 更新条目 url
Uploader->>UI: setFileList(fileListRef.current)
else preview 为 false
Uploader->>UI: setFileList(fileListRef.current)
end
Uploader->>Uploader: 返回 info 并继续入队/上传流程
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Possibly related PRs
Suggested reviewers
Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. 📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/packages/uploader/uploader.tsx (1)
186-205: 修复:map 回调中早返回导致任务丢失与运行时/类型错误当前在 picture 模式且文件非图片时直接
return,会让tasks里出现undefined,随后:
- Line 206/209:
setUploadQueue(tasks)/uploadAction(tasks)会把(UploaderFileItem | undefined)[]传下去;- Line 216:
tasks.map((task) => task.uid)将在运行时报错(task可能为undefined);- TypeScript 也会推断出不匹配的联合类型。
建议仅“跳过预览生成”,不要中断任务创建。可用以下最小改动替换该分支,保证始终
return info:- if (preview) { - // 如果是图片类型的预览且上传的文件非图片则不放入文件列表中 - if (previewType === 'picture' && !file.type?.includes('image')) { - return - } - const reader = new FileReader() - reader.onload = (event: ProgressEvent<FileReader>) => { - fileListRef.current = [ - ...fileListRef.current, - { - ...info, - url: (event.target as FileReader).result as string, - }, - ] - setFileList(fileListRef.current) - } - reader.readAsDataURL(file) - } + // 仅控制是否生成预览;在 picture 模式下非图片不预览,但任务仍然创建 + if (preview && (previewType !== 'picture' || file.type?.startsWith('image/'))) { + const reader = new FileReader() + reader.onload = (event: ProgressEvent<FileReader>) => { + fileListRef.current = [ + ...fileListRef.current, + { + ...info, + url: (event.target as FileReader).result as string, + }, + ] + setFileList(fileListRef.current) + } + reader.readAsDataURL(file) + }这样即可满足“picture 模式只预览图片、list 模式允许非图片预览”的诉求,同时不丢失上传任务。
🧹 Nitpick comments (4)
src/packages/uploader/uploader.tsx (4)
206-210: 兜底防护:在提交前过滤无效任务,避免运行时异常如果暂不修改上面的早返回逻辑,建议先在这里过滤
undefined,以避免uploadAction内部访问task.uid报错。- if (!autoUpload) { - setUploadQueue(tasks) - } else { - await uploadAction(tasks) - } + const validTasks = tasks.filter(Boolean) as UploaderFileItem[] + if (!autoUpload) { + setUploadQueue(validTasks) + } else { + await uploadAction(validTasks) + }
188-188: 文件类型判定更稳健:优先 MIME 前缀,其次扩展名兜底
includes('image')过于宽松且对file.type === ''(常见于部分 iOS/Android 浏览器或拖拽场景)无效。建议改为startsWith('image/'),并提供基于扩展名的兜底:
- 直接替换条件(最小改动):
file.type?.startsWith('image/')- 或新增工具函数,增强鲁棒性(推荐):
function isImageFile(file: File) { if (file.type) return file.type.startsWith('image/') const ext = file.name?.split('.').pop()?.toLowerCase() ?? '' return /^(png|jpe?g|gif|webp|bmp|svg|heic|heif|tiff|ico|avif)$/.test(ext) }随后条件写为:
(previewType !== 'picture' || isImageFile(file))。请在 H5/Android/iOS 三端各测一例确认行为一致。
191-203: 性能优化(可选):list 模式下非图片无需读 DataURL,避免大文件内存开销当前对非图片在 list 模式也会
readAsDataURL,大文件会显著增加内存与耗时。可选择其一:
- 直接将
info入列,不生成url;- 或使用
URL.createObjectURL(file)(记得在删除项或组件卸载时URL.revokeObjectURL)。示例(与上文修复可合并):
- if (preview && (previewType !== 'picture' || file.type?.startsWith('image/'))) { - const reader = new FileReader() - reader.onload = (event: ProgressEvent<FileReader>) => { - fileListRef.current = [ - ...fileListRef.current, - { - ...info, - url: (event.target as FileReader).result as string, - }, - ] - setFileList(fileListRef.current) - } - reader.readAsDataURL(file) - } + if (preview) { + const isImage = file.type?.startsWith('image/') + if (isImage && previewType === 'picture') { + const reader = new FileReader() + reader.onload = (event: ProgressEvent<FileReader>) => { + fileListRef.current = [ + ...fileListRef.current, + { ...info, url: (event.target as FileReader).result as string }, + ] + setFileList(fileListRef.current) + } + reader.readAsDataURL(file) + } else if (previewType === 'list') { + fileListRef.current = [...fileListRef.current, info] + setFileList(fileListRef.current) + } + }
186-203: 补齐用例:覆盖 picture/list 两种预览下的非图片行为为防回归,建议新增以下单测(可使用 JSDOM + jest):
- picture + 非图片:不生成预览条目,但仍创建上传任务(若接受上传);
- list + 非图片:生成列表项预览(无需 DataURL 也可),并确保
setFileList被调用;file.type === ''的图片文件(仅扩展名识别)也能在 picture 模式预览。我可以基于现有测试基建起草测试文件,是否需要我直接补到 PR?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/packages/uploader/uploader.tsx(1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: Jeff-Tian
PR: jdf2e/nutui-react#3151
File: src/packages/uploader/uploader.taro.tsx:435-450
Timestamp: 2025-04-19T14:22:49.844Z
Learning: 在 Uploader 组件中处理图片文件时,FileReader.onload 回调内的 setFileList 调用不能删除,因为它是异步触发的,确保图片读取完成后及时更新状态显示预览。
📚 Learning: 2024-07-05T02:58:57.992Z
Learnt from: Alex-huxiyang
PR: jdf2e/nutui-react#2416
File: src/packages/uploader/uploader.taro.tsx:230-230
Timestamp: 2024-07-05T02:58:57.992Z
Learning: When changes are made to the `fileList` state in the `src/packages/uploader/uploader.taro.tsx` file, ensure to generate unit tests to cover these changes.
Applied to files:
src/packages/uploader/uploader.tsx
📚 Learning: 2025-04-19T14:22:49.844Z
Learnt from: Jeff-Tian
PR: jdf2e/nutui-react#3151
File: src/packages/uploader/uploader.taro.tsx:435-450
Timestamp: 2025-04-19T14:22:49.844Z
Learning: 在 Uploader 组件中处理图片文件时,FileReader.onload 回调内的 setFileList 调用不能删除,因为它是异步触发的,确保图片读取完成后及时更新状态显示预览。
Applied to files:
src/packages/uploader/uploader.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: test
- GitHub Check: build
🔇 Additional comments (1)
src/packages/uploader/uploader.tsx (1)
191-202: 赞:保留了 FileReader.onload 内的 setFileList 异步更新与以往踩坑记录一致,未移除 onload 内的
setFileList,能保证图片读取完成后及时刷新预览列表。
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## feat_v3.x #3343 +/- ##
==========================================
Coverage 88.15% 88.15%
==========================================
Files 291 291
Lines 19212 19212
Branches 2989 2988 -1
==========================================
Hits 16937 16937
Misses 2269 2269
Partials 6 6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (4)
src/packages/uploader/__tests__/uploader.spec.tsx (4)
96-96: 测试名称更明确一些更易读建议将标题从“should render no-image file uploader list”改为“should render non-image items when previewType is list”,更清晰地区分“文件类型”与“预览类型”。
-test('should render no-image file uploader list', () => { +test('should render non-image items when previewType is list', () => {
125-131: 冗余 props:uploadIcon 未参与断言,可删除减少噪音本用例未断言 uploadIcon,可去掉以聚焦“非图片 + 列表预览”的核心行为。
return ( <Uploader defaultValue={defaultFileList} - uploadIcon="dongdong" previewType="list" /> )
134-137: 断言更稳健:补充对文件名文本的断言,并精简变量命名当前通过选择器统计 .list 的数量可能受样式类变动影响而脆弱。建议同时断言文件名文本是否渲染,且用更直观的变量名。
- const { container } = render(<App />) - const toast1 = container.querySelectorAll('.list') - expect(toast1).toBeTruthy() - expect(toast1.length).toBe(3) + const { container, getByText } = render(<App />) + const listItems = container.querySelectorAll('.list') + expect(listItems.length).toBe(3) + // 同时校验文件名文本,提升用例鲁棒性 + expect(getByText('文件1.txt')).toBeInTheDocument() + expect(getByText('文件2.ppt')).toBeInTheDocument() + expect(getByText('文件3.cpp')).toBeInTheDocument()
96-139: 补充反向用例:previewType='picture' 时,非图片应被过滤为防回归,建议新增一条对应的“反向”测试:当 previewType="picture" 且 FileItem.type 非 'image' 时,不应渲染到预览列表中。该用例可放在本测试块之后。
示例代码(新增用例,非 diff,仅供参考):
test('should NOT render non-image items when previewType is picture', () => { const defaultFileList: FileItem[] = [ { name: 'a.txt', url: 'https://example.com/a.txt', status: 'success', type: 'file', uid: 'a' }, { name: 'b.png', url: 'https://example.com/b.png', status: 'success', type: 'image', uid: 'b' }, ] const { container, queryByText } = render( <Uploader defaultValue={defaultFileList} previewType="picture" /> ) // 仅图片应渲染 expect(queryByText('a.txt')).toBeNull() expect(queryByText('b.png')).not.toBeNull() })如果 Taro 端(uploader.taro.tsx)同步调整了相同逻辑,建议在其测试集中也添加等价用例以保持一致性。需要我起草对应 Taro 端用例吗?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/packages/uploader/__tests__/uploader.spec.tsx(1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: Jeff-Tian
PR: jdf2e/nutui-react#3151
File: src/packages/uploader/uploader.taro.tsx:435-450
Timestamp: 2025-04-19T14:22:49.844Z
Learning: 在 Uploader 组件中处理图片文件时,FileReader.onload 回调内的 setFileList 调用不能删除,因为它是异步触发的,确保图片读取完成后及时更新状态显示预览。
📚 Learning: 2024-07-05T02:58:57.992Z
Learnt from: Alex-huxiyang
PR: jdf2e/nutui-react#2416
File: src/packages/uploader/uploader.taro.tsx:230-230
Timestamp: 2024-07-05T02:58:57.992Z
Learning: When changes are made to the `fileList` state in the `src/packages/uploader/uploader.taro.tsx` file, ensure to generate unit tests to cover these changes.
Applied to files:
src/packages/uploader/__tests__/uploader.spec.tsx
🧬 Code graph analysis (1)
src/packages/uploader/__tests__/uploader.spec.tsx (2)
src/packages/uploader/uploader.tsx (1)
Uploader(333-333)src/packages/uploader/uploader.taro.tsx (1)
Uploader(392-392)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: test
- GitHub Check: build
🔇 Additional comments (2)
src/packages/uploader/__tests__/uploader.spec.tsx (2)
96-139: 单测场景契合 PR 目标,覆盖“非图片 + 列表预览”的渲染路径新增用例明确验证了 previewType="list" 时,非图片文件不会被过滤,能正常渲染列表项。这正是本次修复的核心行为。不错。
100-122: 无需修改 FileItem.type —— 该字段并非文件“类型”而是预览模式目前在
src/types/spec/uploader/base.ts中,UploaderFileItem并未声明type字段,仅包含status、message、uid等属性;而在各组单元测试里,type用于区分两种预览样式——'image'(图片预览)与'list'(列表预览),符合组件实际逻辑,无需改为'file'。
- UploaderFileItem 类型定义中无
type属性,说明此字段不是文件本身类型- 测试用例中多处出现
type: 'image'与type: 'list',正是基于预览模式的判断因此,请忽略将
'list'改为'file'的建议,该处保持现有用法即可。Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/packages/uploader/uploader.tsx (1)
186-199: 修正预览条件:picture 模式不应对“所有文件”读 base64;list 模式需将非图片入列展示当前改动把条件放宽为
preview && previewType === 'picture',导致:
- picture 模式下,非图片文件也会被
FileReader.readAsDataURL处理并尝试作为<img>渲染,体验不可控,且与“仅在 picture+非图片时拦截”的需求不符。- list 模式下,新增的非图片不会入列(因为只有该分支里才
setFileList),原 issue「非图片无法显示在预览列表」在实际上传交互中依然存在。建议逻辑:
- picture 模式仅对图片(
/^image\//)走FileReader并入列;- list(或其它)模式直接将文件条目入列,不读数据;
- picture+非图片:按产品诉求拦截预览(不读/不入列,或入列但无 url,二选一)。
可在本段内直接调整为:
- if (preview && previewType === 'picture') { - const reader = new FileReader() - reader.onload = (event: ProgressEvent<FileReader>) => { - fileListRef.current = [ - ...fileListRef.current, - { - ...info, - url: (event.target as FileReader).result as string, - }, - ] - setFileList(fileListRef.current) - } - reader.readAsDataURL(file) - } + if (preview) { + if (previewType === 'picture') { + if (/^image\//.test(file.type)) { + const reader = new FileReader() + reader.onload = (event: ProgressEvent<FileReader>) => { + fileListRef.current = [ + ...fileListRef.current, + { + ...info, + url: (event.target as FileReader).result as string, + }, + ] + setFileList(fileListRef.current) + } + reader.readAsDataURL(file) + } + // 非图片在 picture 模式下不做预览,若需“入列但无图”,可在此 else 分支入列。 + // else { + // fileListRef.current = [...fileListRef.current, info] + // setFileList(fileListRef.current) + // } + } else { + // list 等模式:任何文件直接入列 + fileListRef.current = [...fileListRef.current, info] + setFileList(fileListRef.current) + } + }这样既满足“list 模式允许非图片展示”,也避免 picture 模式对非图片误读 base64。并保留了 onload 中的 setFileList(参考长期经验 Learnings)。
🧹 Nitpick comments (1)
src/packages/uploader/uploader.tsx (1)
186-199: 性能与内存友好性:避免对非图片读 base64,图片也可考虑 ObjectURL
- 读取大文件为 base64 会显著增加内存占用并阻塞主线程,尤其当前实现会在 picture 模式对所有文件执行(本评论上一条已建议收敛到仅图片)。
- 进一步建议:对于图片预览也可以使用
URL.createObjectURL(file)替代FileReader,并在删除/清空时URL.revokeObjectURL,减轻内存压力与延迟。如需我协助在删除逻辑(Lines 142-156 的
deleted)中补充revokeObjectURL,请告知。
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/packages/uploader/uploader.tsx(1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: Jeff-Tian
PR: jdf2e/nutui-react#3151
File: src/packages/uploader/uploader.taro.tsx:435-450
Timestamp: 2025-04-19T14:22:49.844Z
Learning: 在 Uploader 组件中处理图片文件时,FileReader.onload 回调内的 setFileList 调用不能删除,因为它是异步触发的,确保图片读取完成后及时更新状态显示预览。
📚 Learning: 2024-07-05T02:58:57.992Z
Learnt from: Alex-huxiyang
PR: jdf2e/nutui-react#2416
File: src/packages/uploader/uploader.taro.tsx:230-230
Timestamp: 2024-07-05T02:58:57.992Z
Learning: When changes are made to the `fileList` state in the `src/packages/uploader/uploader.taro.tsx` file, ensure to generate unit tests to cover these changes.
Applied to files:
src/packages/uploader/uploader.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: build
- GitHub Check: test
🔇 Additional comments (1)
src/packages/uploader/uploader.tsx (1)
186-199: 补充“真实上传交互”覆盖测试为确保 H5 和 Taro 两端的
Uploader组件在 list 与 picture 模式下对非图片/混合类型文件的上传预览行为均被充分验证,建议:
H5 端(
src/packages/uploader/uploader.tsx)
- 当前
fileChange仅在previewType==='picture'时通过FileReader更新fileList;list 模式下不会即时入列。- 测试中尚未模拟
previewType="list"且真实触发<input type="file">上传的场景,也未对application/pdf、text/plain等非图片文件断言列表新增。测试文件(
src/packages/uploader/__tests__/uploader.spec.tsx)
- 增加一组用例:传入
previewType="list",autoUpload=true(或false),multiple模式下选择单/多份非图片(如 PDF),并断言列表中展示对应名称和状态(url可为空)。- 再增一组用例:
previewType="picture",混合选择图片与非图片,断言只有图片条目带url(Base64/ObjectURL),非图片不含url。Taro 端(
src/packages/uploader/uploader.taro.tsx)
- 经确认已无基于
file.type?.includes('image')的老逻辑过滤,readFile会对所有文件(图片/非图片)按preview参数一视同仁入列,故无需同步修改。可参考示例片段,在
__tests__/uploader.spec.tsx中新增:test('list 模式下非图片应立即入列', async () => { const { container, findByText } = render( <Uploader previewType="list" multiple autoUpload={true} /> ) const file = new File([new ArrayBuffer(16)], 'doc.pdf', { type: 'application/pdf', }) const input = container.querySelector('input[type="file"]')! await fireEvent.change(input, { target: { files: [file] } }) // 断言:列表中出现 “doc.pdf”、状态为 ready/uploading(取决 autoUpload) expect(await findByText('doc.pdf')).toBeInTheDocument() }) test('picture 模式下混合文件仅图片带 url', async () => { const { container, findAllByRole } = render( <Uploader previewType="picture" multiple autoUpload={false} /> ) const img = new File([''], 'a.png', { type: 'image/png' }) const txt = new File([''], 'a.txt', { type: 'text/plain' }) const input = container.querySelector('input[type="file"]')! await fireEvent.change(input, { target: { files: [img, txt] } }) const previews = await findAllByRole('img') // 只有图片产生 <img> 预览 expect(previews.length).toBe(1) expect(previews[0]).toHaveAttribute('src', expect.stringContaining('data:image')) }请酌情补充相应的 mock
FileReader/URL.createObjectURL,并将测试覆盖至 H5 与 Taro 两端。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/packages/uploader/uploader.tsx (1)
186-199: 请在 src/packages/uploader/uploader.tsx 中按文件类型与 previewType 分流预览逻辑
- 当前位置(约 186–199 行)
if (preview)分支对所有文件(包括非图片)均使用 FileReader → dataURL 并追加至fileListRef.current,导致在picture模式下非图片也加入预览,且与 PR “仅在预览类型为图片且文件本身不是图片时才拦截” 的设计不符。- 应根据
isImage = /^image\//.test(file.type || '')与previewType值分别处理:
- picture + 图片:保留现有 FileReader 逻辑;
- picture + 非图片:不加入预览列表(但继续上传流程);
- list + 非图片:无需 dataURL,直接追加
info,由 Preview 负责渲染图标/名称。建议最小化改动,替换原有代码块为:
- if (preview) { - const reader = new FileReader() - reader.onload = (event: ProgressEvent<FileReader>) => { - fileListRef.current = [ - ...fileListRef.current, - { - ...info, - url: (event.target as FileReader).result as string, - }, - ] - setFileList(fileListRef.current) - } - reader.readAsDataURL(file) - } + const isImage = /^image\//.test(file.type || '') + if (preview) { + if (previewType === 'picture' && !isImage) { + // picture 模式下非图片不加入预览列表 + } else if (isImage) { + const reader = new FileReader() + reader.onload = (event: ProgressEvent<FileReader>) => { + fileListRef.current = [ + ...fileListRef.current, + { + ...info, + url: (event.target as FileReader).result as string, + }, + ] + setFileList(fileListRef.current) + } + reader.readAsDataURL(file) + } else { + // list 模式下非图片直接追加,无需转换为 dataURL + fileListRef.current = [...fileListRef.current, info] + setFileList(fileListRef.current) + } + }此改动仍保留
FileReader.onload回调内的setFileList调用,以确保图片异步读取完成后状态能正确更新并展示预览(参考长期学习记录)。
🧹 Nitpick comments (1)
src/packages/uploader/uploader.tsx (1)
186-199: 避免对非图片大文件使用 dataURL,降低内存与主线程占用
- 对 PDF/视频/二进制大文件直接 readAsDataURL 会显著放大体积(~133% base64 膨胀)并阻塞主线程,且 list 预览并不需要内容 URL。
- 建议:
- list 预览非图片:如上所示直接 append,不读取内容;
- 如需为图片/视频生成预览,优先考虑 URL.createObjectURL,并在删除或组件卸载时 revokeObjectURL,避免内存泄漏(需要在删除回调与 useEffect 清理中补充 revoke,属后续可选优化)。
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/packages/uploader/uploader.tsx(1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: Jeff-Tian
PR: jdf2e/nutui-react#3151
File: src/packages/uploader/uploader.taro.tsx:435-450
Timestamp: 2025-04-19T14:22:49.844Z
Learning: 在 Uploader 组件中处理图片文件时,FileReader.onload 回调内的 setFileList 调用不能删除,因为它是异步触发的,确保图片读取完成后及时更新状态显示预览。
📚 Learning: 2024-07-05T02:58:57.992Z
Learnt from: Alex-huxiyang
PR: jdf2e/nutui-react#2416
File: src/packages/uploader/uploader.taro.tsx:230-230
Timestamp: 2024-07-05T02:58:57.992Z
Learning: When changes are made to the `fileList` state in the `src/packages/uploader/uploader.taro.tsx` file, ensure to generate unit tests to cover these changes.
Applied to files:
src/packages/uploader/uploader.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: test
- GitHub Check: build
🔇 Additional comments (1)
src/packages/uploader/uploader.tsx (1)
186-199: 请手动确认测试覆盖情况为了避免 “uploading” 状态在
previewType="picture"模式下因异步时序问题而短暂缺失,请务必人工检查以下两点:
- 仓库中是否已有覆盖
previewType="picture"场景的单元测试/集成测试- 仓库中是否已有覆盖非图片 MIME(如
text/*、application/*)上传时的测试用例如无,请补充对应测试,确保在图片和非图片文件都启用
autoUpload=true时,「上传中」标记始终正确展示。
🤔 这个变动的性质是?
🔗 相关 Issue
#3333
上传非图片无法进行预览列表
💡 需求背景和解决方案
问题:在设置文件列表时,校验非图片直接拦截,导致无法预览
解决:在拦截时,校验预览类型为图片且非图片才拦截
☑️ 请求合并前的自查清单
Summary by CodeRabbit
Bug 修复 / 行为变更
Tests