⚠️ 必须先保存后台数据,再上传文件,避免孤立的COS资源!
const cosUtil = require('../../lib/cosUtil.js')
// ❌ 错误方式:先上传文件再保存数据
// 如果保存数据失败,会产生孤立的COS文件
// ✅ 正确方式:先保存用户数据,再上传头像
async function registerWithAvatar() {
try {
// 步骤1: 先提交注册数据(不包含头像)
const registrationResult = await submitRegistration({
name: '张三',
phone: '13800138000',
// ... 其他数据
})
const registrationId = registrationResult.registrationId
// 步骤2: 注册成功后,再上传头像
const avatarResult = await cosUtil.chooseAndUploadImage({
count: 1,
sizeType: ['compressed']
}, 'avatar', (progress) => {
console.log('头像上传进度:', progress + '%')
})
// 步骤3: 保存头像媒体记录到后台
await saveMediaRecord({
fileName: avatarResult.fileName,
filePath: avatarResult.key,
fileSize: avatarResult.fileSize,
fileType: 'image/jpeg',
storageType: 'COS',
bucketName: 'ryc-1379367838',
region: 'ap-chengdu',
targetType: 6, // STUDENT_AVATAR
targetId: registrationId
})
console.log('注册和头像上传完成')
} catch (error) {
console.error('注册失败:', error)
// 如果有已上传的文件,需要清理
if (avatarResult && avatarResult.key) {
await cosUtil.deleteFile(avatarResult.key)
}
}
}
// 选择并上传头像
cosUtil.chooseAndUploadImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera']
}, 'avatar', (progress) => {
console.log('头像上传进度:', progress + '%')
}).then(result => {
console.log('头像上传成功:', result)
// result.key: 文件在COS中的路径
// result.url: 文件访问URL
// result.fileName: 生成的唯一文件名
}).catch(error => {
console.error('头像上传失败:', error)
})
// 选择并上传图片
cosUtil.chooseAndUploadImage({
count: 9, // 最多9张
sizeType: ['original', 'compressed']
}, 'image', (progress) => {
console.log('图片上传进度:', progress + '%')
}).then(results => {
console.log('图片上传成功:', results)
}).catch(error => {
console.error('图片上传失败:', error)
})
// 选择并上传视频
cosUtil.chooseAndUploadVideo({
sourceType: ['album', 'camera'],
maxDuration: 60, // 最长60秒
camera: 'back'
}, (progress) => {
console.log('视频上传进度:', progress + '%')
}).then(result => {
console.log('视频上传成功:', result)
}).catch(error => {
console.error('视频上传失败:', error)
})
// 直接上传指定文件
cosUtil.uploadFile(
'wxfile://tmp_xxx.jpg', // 本地文件路径
'image', // 文件类型
'my-photo.jpg', // 原始文件名
(progress) => {
console.log('上传进度:', progress + '%')
}
).then(result => {
console.log('文件上传成功:', result)
}).catch(error => {
console.error('文件上传失败:', error)
})
const files = [
{ filePath: 'wxfile://tmp_1.jpg', fileType: 'image', originalName: 'photo1.jpg' },
{ filePath: 'wxfile://tmp_2.jpg', fileType: 'image', originalName: 'photo2.jpg' },
{ filePath: 'wxfile://tmp_3.mp4', fileType: 'video', originalName: 'video1.mp4' }
]
cosUtil.batchUpload(files, (fileIndex, progress, totalFiles) => {
console.log(`文件 ${fileIndex + 1}/${totalFiles} 上传进度: ${progress}%`)
}).then(results => {
console.log('批量上传成功:', results)
}).catch(error => {
console.error('批量上传失败:', error)
})
const fileUrl = cosUtil.getFileUrl('images/20241201/1234567890_abc123.jpg')
console.log('文件访问地址:', fileUrl)
cosUtil.deleteFile('images/20241201/1234567890_abc123.jpg').then(() => {
console.log('文件删除成功')
}).catch(error => {
console.error('文件删除失败:', error)
})
工具类会自动按照后台规范生成文件路径:
avatars/yyyyMMdd/timestamp_random.ext
images/yyyyMMdd/timestamp_random.ext
videos/yyyyMMdd/timestamp_random.ext
attachments/yyyyMMdd/timestamp_random.ext
try {
const result = await cosUtil.uploadAvatar(filePath, originalName)
// 上传成功处理
} catch (error) {
if (error.code === 'NoSuchBucket') {
console.error('存储桶不存在')
} else if (error.code === 'AccessDenied') {
console.error('访问被拒绝,请检查密钥配置')
} else {
console.error('上传失败:', error.message)
}
}