Skip to content

Conversation

@holyfata
Copy link
Contributor

@holyfata holyfata commented Aug 21, 2025

🤔 这个变动的性质是?

  • 新特性提交
  • 日常 bug 修复
  • 站点、文档改进
  • 演示代码改进
  • 组件样式/交互改进
  • TypeScript 定义更新
  • 包体积优化
  • 性能优化
  • 功能增强
  • 国际化改进
  • 重构
  • 代码风格优化
  • 测试用例
  • 分支合并
  • 其他改动(是关于什么的改动?)

🔗 相关 Issue

#3333
上传非图片无法进行预览列表

💡 需求背景和解决方案

问题:在设置文件列表时,校验非图片直接拦截,导致无法预览
解决:在拦截时,校验预览类型为图片且非图片才拦截

☑️ 请求合并前的自查清单

⚠️ 请自检并全部勾选全部选项⚠️

  • 文档已补充或无须补充
  • 代码演示已提供或无须提供
  • TypeScript 定义已补充或无须补充
  • fork仓库代码是否为最新避免文件冲突
  • Files changed 没有 package.json lock 等无关文件

Summary by CodeRabbit

  • Bug 修复 / 行为变更

    • 预览逻辑从仅图片扩展为所有启用预览的文件:在启用预览时会为所有文件生成并显示预览 URL,已存在列表项会被更新为包含该 URL;上传流程与对外接口保持不变。
  • Tests

    • 新增用例验证列表预览模式下能正确渲染多种非图片文件项(不同状态,共三项)。

@coderabbitai
Copy link

coderabbitai bot commented Aug 21, 2025

Walkthrough

将文件加入时立即把 per-file 信息追加到 fileListRef.current;当 preview 为真时,FileReader 会为所有文件生成 URL 并在 onload 中更新对应条目的 url,随后通过 setFileList 同步可见列表。新增测试覆盖非图片列表渲染。

Changes

Cohort / File(s) Summary of changes
Uploader 文件列表与预览处理
src/packages/uploader/uploader.tsx
将 per-file info 立即追加到 fileListRef.current;将原先仅针对图片的 FileReader 预览条件改为仅依赖 preview,FileReader.onload 会向已有条目添加/更新 url 并通过 setFileList(fileListRef.current) 同步可见列表;导出签名等接口未变更。
测试:非图片列表渲染
src/packages/uploader/__tests__/uploader.spec.tsx
新增用例 should render no-image file uploader list:构造三项非图片 defaultFileList,以 previewType="list" 渲染 Uploader,并断言渲染出 3 个 .list 项。

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 并继续入队/上传流程
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • Alex-huxiyang
  • oasis-cloud
  • xiaoyatong

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 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.

📥 Commits

Reviewing files that changed from the base of the PR and between f4237c6 and f931948.

📒 Files selected for processing (1)
  • src/packages/uploader/uploader.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • 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
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added action:review This PR needs more reviews (less than 2 approvals) 3.x Target branch 3.x labels Aug 21, 2025
Copy link

@coderabbitai coderabbitai bot left a 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 3dbc7bc and a723ff1.

📒 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
Copy link

codecov bot commented Aug 21, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.15%. Comparing base (3dbc7bc) to head (f931948).
⚠️ Report is 1 commits behind head on feat_v3.x.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@coderabbitai coderabbitai bot left a 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 0b7372b and 6372ec4.

📒 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 字段,仅包含 statusmessageuid 等属性;而在各组单元测试里,type 用于区分两种预览样式——'image'(图片预览)与 'list'(列表预览),符合组件实际逻辑,无需改为 'file'

  • UploaderFileItem 类型定义中无 type 属性,说明此字段不是文件本身类型
  • 测试用例中多处出现 type: 'image'type: 'list',正是基于预览模式的判断

因此,请忽略将 'list' 改为 'file' 的建议,该处保持现有用法即可。

Likely an incorrect or invalid review comment.

@Miles-hxy Miles-hxy changed the title feat: 处理非图片文件类型问题 fix(uploader): 处理非图片文件类型问题 Aug 22, 2025
Copy link

@coderabbitai coderabbitai bot left a 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 6372ec4 and c5e999f.

📒 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/pdftext/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 FileReaderURL.createObjectURL,并将测试覆盖至 H5 与 Taro 两端。

Copy link

@coderabbitai coderabbitai bot left a 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.

📥 Commits

Reviewing files that changed from the base of the PR and between c5e999f and f0ba4c8.

📒 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 时,「上传中」标记始终正确展示。

@Miles-hxy Miles-hxy merged commit dcfd2f0 into jdf2e:feat_v3.x Aug 22, 2025
8 checks passed
@holyfata holyfata deleted the feature_hyq-FEATV3X-uploader-20250821-nopng branch September 6, 2025 17:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

3.x Target branch 3.x action:review This PR needs more reviews (less than 2 approvals) size/M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants