第 13 章:文件上传与云存储
"一张图胜过千言万语,但前提是你得把图传上去。"
本章将讲解如何利用腾讯云开发 (CloudBase) 的云存储能力,实现高效、稳定的文件上传。
13.1 云存储架构
云存储 (Cloud Storage) 本质上是一个对象存储服务 (COS)。
- 路径 : 我们按照
year/month/filename的格式组织文件,避免单目录下文件过多。 - 权限: 默认设置为"所有用户可读,仅创建者/管理员可写"。
13.2 图片/视频上传实现
前端核心 API: uniCloud.uploadFile。
封装上传 Hook (useUpload)
为了复用,我们封装了一个 Hook:
typescript
// src/hooks/useUpload.ts
export function useUpload() {
const uploadImage = async (filePath: string) => {
const ext = filePath.split('.').pop()
const cloudPath = `activity/${Date.now()}-${Math.random().toString(36).slice(-6)}.${ext}`
uni.showLoading({ title: '上传中...' })
try {
const res = await uniCloud.uploadFile({
filePath: filePath,
cloudPath: cloudPath
})
return res.fileID // 返回 cloud://...
} finally {
uni.hideLoading()
}
}
return { uploadImage }
}
选择文件
结合 uni.chooseImage 或 uni.chooseVideo:
javascript
const chooseAndUpload = async () => {
const res = await uni.chooseImage({ count: 1 })
const filePath = res.tempFilePaths[0]
const fileID = await uploadImage(filePath)
// 将 fileID 存入组件配置或表单
config.src = fileID
}
13.3 FileID 与临时 URL 转换
CloudID (cloud://...) 是云开发的特有协议。
- 在小程序内 :
<image src="cloud://...">可以直接展示,无需转换,利用内网 CDN,速度极快。 - 在 Web/H5 端 : 浏览器不认识
cloud://。需要调用uniCloud.getTempFileURL换取https://开头的临时链接。
最佳实践 : 尽量在数据库存
cloud://路径。只在需要在非小程序环境展示时才进行转换。
13.4 批量上传优化
在"活动相册"或"多图投票"场景下,用户可能一次选 9 张图。 串行 vs 并行:
- ❌ 串行: 传完一张再传下一张,太慢。
- ✅ 并行:
Promise.all。
javascript
const uploadAll = async (paths) => {
const tasks = paths.map((path) => uploadImage(path))
const fileIDs = await Promise.all(tasks)
return fileIDs
}
本章小结: 文件上传是内容类应用的基础设施。有了云存储,我们不再需要操心文件服务器的搭建和带宽费用,只需关注业务逻辑。下一章,我们将为活动添加一些"氛围组"功能------背景音乐和弹幕。