Skip to content
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

feat(download): optimize file download handling #574

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Faizele
Copy link
Contributor

@Faizele Faizele commented Mar 22, 2025

  • Add JSON error response handling for blob downloads
  • Return structured download response with data, filename and headers
  • Add downloadFile utility function

Summary by CodeRabbit

  • 新功能

    • 新增文件下载功能,支持通过HTTP请求下载文件,并提供实时下载进度反馈,同时确保跨浏览器兼容性。
  • 改进

    • 优化了下载响应处理流程,增强了错误提示和文件名提取能力,使下载体验更加顺畅和可靠。

- Add JSON error response handling for blob downloads
- Return structured download response with data, filename and headers
- Add downloadFile utility function
@dosubot dosubot bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Mar 22, 2025
Copy link

coderabbitai bot commented Mar 22, 2025

📝 Walkthrough

Walkthrough

此次变更在 web/src/utils/download.ts 中新增了一个 downloadFile 工具函数,通过 HTTP 请求实现文件下载,并提供下载进度回调,同时新增了 DownloadOptionsDownloadResponse 接口;在 web/src/utils/http.ts 中,对响应拦截器的 Blob 和 ArrayBuffer 响应做了改进,增加了对 JSON 格式错误内容的处理以及对 content-disposition 头部解析文件名的逻辑。

Changes

文件路径 变更概要
web/src/utils/download.ts 新增 downloadFile 函数及 DownloadOptionsDownloadResponse 接口,通过 HTTP 请求获取 Blob 数据,并针对 IE 和其他浏览器分别采用不同的文件保存方式。
web/src/utils/http.ts 响应拦截器调整:当响应为 Blob 或 ArrayBuffer 时,利用 FileReader 解析 JSON 错误信息;若为文件下载响应,则从 content-disposition 提取并解码文件名。

Sequence Diagram(s)

Loading
sequenceDiagram
    participant C as 调用者
    participant DF as downloadFile
    participant HTTP as request.http
    participant Browser as 浏览器API

    C->>DF: 调用 downloadFile(options)
    DF->>HTTP: 发起 HTTP 请求 (responseType: 'blob')
    HTTP-->>DF: 返回 Blob 数据
    DF->>Browser: 检查 msSaveOrOpenBlob 方法
    alt IE 支持
        DF->>Browser: 使用 msSaveOrOpenBlob 保存文件
    else 非IE浏览器
        DF->>Browser: 创建临时 anchor 元素并触发点击下载
    end
    DF->>Browser: 撤销对象 URL (清理资源)
Loading
sequenceDiagram
    participant Interceptor as 响应拦截器
    participant Resp as HTTP 响应
    participant Reader as FileReader
    participant UI as 用户界面

    Interceptor->>Resp: 接收 Blob/ArrayBuffer 响应
    alt 响应为 JSON 格式 Blob
        Interceptor->>Reader: 调用 readAsText 处理 Blob
        Reader-->>Interceptor: 返回文本数据
        Interceptor->>Interceptor: 解析文本为 JSON 并检查错误码
        Interceptor->>UI: 显示错误信息并拒绝 Promise
    else 成功下载响应
        Interceptor->>Interceptor: 提取 content-disposition 解析文件名
        Interceptor->>UI: 返回包含文件名、数据与头部的成功响应
    end

Poem

我是一只跳跃的兔子,代码如草原般宽广,
新增的下载函数,让文件传输飞扬。
响应拦截变得细腻,错误解析不再迷航,
各浏览器齐心协力,数据传递轻松畅享。
在键盘上我欢快起舞,庆祝这一切更新的奇妙光芒 🐇✨。

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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 or PR title anywhere in the PR title to generate the title automatically.

Documentation and Community

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

Sorry, something went wrong.

@dosubot dosubot bot added the enhancement label Mar 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

🧹 Nitpick comments (2)
web/src/utils/http.ts (1)

64-95: 增强了对二进制响应类型的处理

这部分代码改进了对 blob 和 arraybuffer 响应类型的处理逻辑,特别是添加了对 JSON 格式错误响应的处理以及从 content-disposition 头部提取文件名的功能。这些改进对于文件下载功能非常重要。

有几点可以进一步优化:

  1. 在解析 JSON 结果时,应该先检查 result 对象是否包含 code 属性,以避免潜在的错误。
  2. 在读取 blob 数据时,应该确保在所有情况下都正确地解决或拒绝 Promise。
  3. 使用可选链操作符可以使代码更加安全。

以下是建议的改进:

  if (response.data instanceof Blob && response.data.type === 'application/json') {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = () => {
        const result = JSON.parse(reader.result as string)
-       if (result.code !== ResultCode.SUCCESS) {
+       if (result && result.code !== ResultCode.SUCCESS) {
          Message.error(result.message || '下载失败', { zIndex: 9999 })
          reject(result)
+       } else {
+         resolve(result)
        }
      }
+     reader.onerror = () => {
+       reject(new Error('解析响应数据时出错'))
+     }
      reader.readAsText(response.data)
    })
  }

  // 正常的文件下载响应
  const disposition = response.headers['content-disposition']
  let fileName = '未命名文件'
  if (disposition) {
    const match = disposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
-   if (match && match[1]) {
-     fileName = decodeURIComponent(match[1].replace(/['"]/g, ''))
+   if (match) {
+     fileName = decodeURIComponent(match[1]?.replace(/['"]/g, '') || fileName)
    }
  }
🧰 Tools
🪛 Biome (1.9.4)

[error] 86-87: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

web/src/utils/download.ts (1)

23-71: 新增文件下载工具函数实现

新增的downloadFile函数提供了一个灵活的文件下载解决方案,支持进度跟踪、自定义文件名和MIME类型等功能。这个实现考虑了跨浏览器兼容性,并正确处理了资源释放。

有几点可以进一步完善:

  1. 在创建Blob和使用navigator.msSaveOrOpenBlob时可以使用可选链操作符增强代码安全性。
  2. 对于进度回调函数,可以添加错误处理机制。
  3. 应考虑添加错误处理逻辑,当下载失败时提供用户反馈。

以下是建议的改进:

  // 创建 Blob
  const blob = new Blob([response.data], {
    type: mimeType || response.headers['content-type'],
  })

- if (window.navigator && window.navigator.msSaveOrOpenBlob) {
+ if (window.navigator?.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, downloadFileName)
    return
  }

  const downloadUrl = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = downloadUrl
  link.download = downloadFileName
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(downloadUrl)

另外,建议添加try/catch块来处理可能的错误:

export async function downloadFile(options: DownloadOptions) {
  const {
    url,
    method = 'GET',
    data,
    fileName,
    mimeType,
    onProgress,
  } = options

  try {
    const response = await request.http({
      // ... 保持现有代码不变
    }) as DownloadResponse

    // ... 保持现有代码不变

  } catch (error) {
    console.error('文件下载失败:', error)
    // 可以添加自定义错误处理逻辑,例如显示通知
    throw error
  }
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 57-58: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa508ba and c01e51b.

📒 Files selected for processing (2)
  • web/src/utils/download.ts (1 hunks)
  • web/src/utils/http.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
web/src/utils/download.ts

[error] 57-58: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

web/src/utils/http.ts

[error] 86-87: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Test on PHP8.1 Swoole-v5.1.5
  • GitHub Check: Test on PHP8.1 Swoole-master
  • GitHub Check: Test on PHP8.2 Swoole-master
  • GitHub Check: Test on PHP8.3 Swoole-master
  • GitHub Check: Test on PHP8.1 Swoole-v5.0.3
  • GitHub Check: Test on PHP8.2 Swoole-v5.0.3
  • GitHub Check: Test on PHP8.3 Swoole-v5.1.5
  • GitHub Check: Test on PHP8.2 Swoole-v5.1.5
  • GitHub Check: Test on PHP8.3 Swow-develop
  • GitHub Check: Test on PHP8.1 Swow-develop
  • GitHub Check: Test on PHP8.2 Swow-develop
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: build Code coverage report (ubuntu-latest, 8.1, v5.1.3)
🔇 Additional comments (1)
web/src/utils/download.ts (1)

1-22: 文件下载相关的类型定义

这部分代码定义了下载选项和下载响应的接口,使用TypeScript类型系统提供了良好的类型安全性。

@zds-s zds-s requested a review from kanyxmo March 23, 2025 03:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement size:L This PR changes 100-499 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants