-
Notifications
You must be signed in to change notification settings - Fork 186
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
base: master
Are you sure you want to change the base?
Conversation
- Add JSON error response handling for blob downloads - Return structured download response with data, filename and headers - Add downloadFile utility function
📝 WalkthroughWalkthrough此次变更在 Changes
Sequence Diagram(s)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 (清理资源)
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
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:
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)
Other keywords and placeholders
Documentation and Community
|
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 (2)
web/src/utils/http.ts (1)
64-95
: 增强了对二进制响应类型的处理这部分代码改进了对 blob 和 arraybuffer 响应类型的处理逻辑,特别是添加了对 JSON 格式错误响应的处理以及从 content-disposition 头部提取文件名的功能。这些改进对于文件下载功能非常重要。
有几点可以进一步优化:
- 在解析 JSON 结果时,应该先检查 result 对象是否包含 code 属性,以避免潜在的错误。
- 在读取 blob 数据时,应该确保在所有情况下都正确地解决或拒绝 Promise。
- 使用可选链操作符可以使代码更加安全。
以下是建议的改进:
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类型等功能。这个实现考虑了跨浏览器兼容性,并正确处理了资源释放。有几点可以进一步完善:
- 在创建Blob和使用navigator.msSaveOrOpenBlob时可以使用可选链操作符增强代码安全性。
- 对于进度回调函数,可以添加错误处理机制。
- 应考虑添加错误处理逻辑,当下载失败时提供用户反馈。
以下是建议的改进:
// 创建 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
📒 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类型系统提供了良好的类型安全性。
Summary by CodeRabbit
新功能
改进