const chooseAndUploadFiles = (
fileType: string | null,
maxCount: number,
isCover: boolean = false
) => {
// 如果已经有文件,只允许上传相同类型的文件
const mediaType: ('image' | 'video' | 'mix')[] =
fileType === 'image' ? ['image'] : fileType === 'video' ? ['video'] : ['mix']
uni.chooseMedia({
count: maxCount,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
mediaType: mediaType,
success: function (res) {
console.log(res, 'res')
const tempFilePaths = res.tempFiles
// 检查是否同时包含图片和视频
const hasImage = tempFilePaths.some((item) => item.fileType === 'image')
const hasVideo = tempFilePaths.some((item) => item.fileType === 'video')
if (hasImage && hasVideo) {
uni.showToast({ icon: 'none', title: '只能上传图片或视频中的一种' })
return
}
// 如果选择的是视频,限制只能上传一个
if (hasVideo && tempFilePaths.length > 1) {
uni.showToast({ icon: 'none', title: '视频只能上传一个' })
return
}
uni.showLoading({
title: '上传中'
})
const uploadPromises = tempFilePaths.map((file) => {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: hasVideo ? BASE_Video_UPLOADURL : BASE_UPLOADURL,
filePath: file.tempFilePath,
name: 'file',
header: {
Authorization: usePersistCommonStore().token
},
success: (uploadFileRes) => {
try {
const data = JSON.parse(uploadFileRes.data)
console.log(data, 'data')
if (isCover) {
formData.value.coverUrl = data.data
}
if (file.fileType === 'image' && !isCover) {
formData.value.images.push(data.data)
} else if (file.fileType === 'video' && !isCover) {
formData.value.videoUrl = data?.data?.url || ''
videoCover.value = data?.data?.capture || ''
if (!formData.value.coverUrl) {
formData.value.coverUrl = data?.data?.capture || ''
}
}
resolve(data)
} catch (error) {
reject(error)
}
},
fail: (error) => {
console.error('上传失败详情:', error)
// 记录更详细的错误信息,包括网络状态、文件大小等
console.log('上传文件信息:', {
fileType: file.fileType,
size: file.size,
path: file.tempFilePath
})
console.log('上传配置:', {
url: hasVideo ? BASE_Video_UPLOADURL : BASE_UPLOADURL,
token: !!usePersistCommonStore().token
})
reject(error)
},
complete: () => {
// 由于Promise.all会等待所有上传完成,这里不需要单独处理loading
}
})
})
})
// 等待所有文件上传完成
Promise.all(uploadPromises)
.then(() => {
uni.hideLoading()
})
.catch((error) => {
console.error('Promise.all 上传失败:', error)
uni.hideLoading()
uni.showToast({ icon: 'none', title: '您的网络环境不稳定或存在波动,请稍后再试。' })
})
}
})
}
f***@163.com (作者)
整个代码吗
2025-11-06 16:44