Files
yimo-resource-blog/utils/qiniu.js
2026-09-16 16:49:25 +08:00

46 lines
1.5 KiB
JavaScript

import { getPointTaskUploadToken } from '@/api/app/index.js'
function fileNameFromPath(path) {
const clean = String(path || '').split('?')[0]
return clean.substring(clean.lastIndexOf('/') + 1) || ('task-' + Date.now() + '.jpg')
}
function contentTypeOf(file) {
if (file && file.type) return file.type
const name = fileNameFromPath(file && file.path)
const ext = name.substring(name.lastIndexOf('.') + 1).toLowerCase()
if (ext === 'png') return 'image/png'
if (ext === 'webp') return 'image/webp'
return 'image/jpeg'
}
/** 小程序直传任务截图到七牛云。 */
export function uploadPointTaskImage(file) {
const filePath = file.path || file.tempFilePath
const fileName = file.name || fileNameFromPath(filePath)
const fileSize = Number(file.size || 0)
const contentType = contentTypeOf(file)
return getPointTaskUploadToken({ fileName, fileSize, contentType }).then(response => {
const data = response.data || {}
return new Promise((resolve, reject) => {
uni.uploadFile({
url: data.uploadHost,
filePath: filePath,
name: 'file',
formData: {
token: data.uploadToken,
key: data.objectKey
},
success: result => {
if (result.statusCode >= 200 && result.statusCode < 300) {
resolve({ objectKey: data.objectKey, localPath: filePath })
return
}
reject(new Error('七牛上传失败,请重试'))
},
fail: reject
})
})
})
}