import config from '@/config'
|
|
|
|
/**
|
|
* OSS直传上传功能(无需后端接口)
|
|
* @param {Object} file - 文件对象(uni.chooseImage返回的文件)
|
|
* @returns {Promise<Object>} 返回上传结果
|
|
*/
|
|
const uploadImage = async (file) => {
|
|
try {
|
|
// 使用项目配置中的OSS信息
|
|
const ossConfig = {
|
|
accessKey: config.aliOSS_accessKey,
|
|
secretKey: config.aliOSS_secretKey,
|
|
bucket: config.aliOSS_bucketName,
|
|
endpoint: config.endpoint,
|
|
staticDomain: config.staticDomain
|
|
}
|
|
|
|
// 生成唯一文件名
|
|
const timestamp = Date.now()
|
|
const randomStr = Math.random().toString(36).substring(2, 8)
|
|
const fileExtension = getFileExtension(file.name || file.path || '.jpg')
|
|
const fileName = `avatars/${timestamp}_${randomStr}${fileExtension}`
|
|
|
|
// 使用公共读写bucket方案(无需签名)
|
|
const uploadUrl = `https://${ossConfig.bucket}.${ossConfig.endpoint}`
|
|
|
|
const result = await uni.uploadFile({
|
|
url: uploadUrl,
|
|
filePath: file.path || file.tempFilePath,
|
|
name: 'file',
|
|
formData: {
|
|
'key': fileName
|
|
}
|
|
})
|
|
|
|
console.log('OSS上传结果:', result)
|
|
|
|
// OSS上传成功的状态码通常是204
|
|
if (result.statusCode === 204 || result.statusCode === 200) {
|
|
const fileUrl = `${ossConfig.staticDomain}${fileName}`
|
|
return {
|
|
success: true,
|
|
url: fileUrl,
|
|
fileName: fileName
|
|
}
|
|
} else {
|
|
throw new Error(`OSS上传失败,状态码: ${result.statusCode}`)
|
|
}
|
|
} catch (error) {
|
|
console.error('OSS上传失败:', error)
|
|
return {
|
|
success: false,
|
|
error: error.message || 'OSS上传失败'
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
* 获取文件扩展名
|
|
*/
|
|
const getFileExtension = (fileName) => {
|
|
if (!fileName) return '.jpg'
|
|
const lastDot = fileName.lastIndexOf('.')
|
|
return lastDot !== -1 ? fileName.substring(lastDot) : '.jpg'
|
|
}
|
|
|
|
/**
|
|
* 选择并上传图片到OSS(一步到位)
|
|
*/
|
|
const chooseAndUpload = async () => {
|
|
try {
|
|
// 选择图片
|
|
const chooseResult = await uni.chooseImage({
|
|
count: 1,
|
|
sizeType: ['compressed'],
|
|
sourceType: ['album', 'camera']
|
|
})
|
|
|
|
if (chooseResult.tempFilePaths && chooseResult.tempFilePaths.length > 0) {
|
|
const file = {
|
|
path: chooseResult.tempFilePaths[0],
|
|
tempFilePath: chooseResult.tempFilePaths[0]
|
|
}
|
|
|
|
// 显示加载提示
|
|
uni.showLoading({ title: '上传到OSS中...' })
|
|
|
|
// 上传文件到OSS
|
|
const uploadResult = await uploadImage(file)
|
|
|
|
uni.hideLoading()
|
|
|
|
if (uploadResult.success) {
|
|
uni.showToast({ title: 'OSS上传成功', icon: 'success' })
|
|
return uploadResult
|
|
} else {
|
|
uni.showToast({ title: uploadResult.error, icon: 'error' })
|
|
return null
|
|
}
|
|
}
|
|
} catch (error) {
|
|
uni.hideLoading()
|
|
uni.showToast({ title: 'OSS上传失败', icon: 'error' })
|
|
console.error('OSS上传失败:', error)
|
|
return null
|
|
}
|
|
}
|
|
|
|
export {
|
|
uploadImage,
|
|
chooseAndUpload,
|
|
getFileExtension
|
|
}
|