@tplc/business
Version:
105 lines (101 loc) • 2.77 kB
text/typescript
import { ref, Ref } from 'vue'
import { uploadByUrl } from './useUpload.api'
/**
* useUpload 是一个定制化的请求钩子,用于处理上传图片。
* @param formData 额外传递给后台的数据,如{name: '菲鸽'}。
* @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。
*/
export default function useUpload(onSuccess?: (url: string) => void) {
const data = ref<string>('')
const run = () => {
// #ifdef MP-WEIXIN
uni.chooseMedia({
count: 1,
mediaType: ['image'],
success: (res) => {
const filePath = res.tempFiles[0].tempFilePath
const name = filePath.split('/').pop() || ''
uploadFile({ filePath, data, name, onSuccess })
},
fail: (err) => {
console.error('uni.chooseMedia err->', err)
},
})
// #endif
// #ifndef MP-WEIXIN
uni.chooseImage({
count: 1,
success: (res: any) => {
const name = res.tempFiles[0].name
uploadFile({ data, name, filePath: res.tempFilePaths[0], onSuccess })
},
fail: (err) => {
console.error('uni.chooseImage err->', err)
},
})
// #endif
}
return { data, run }
}
export async function uploadFile({
filePath,
data,
name,
onSuccess,
}: {
filePath: string
data?: Ref<string>
name: string
onSuccess?: (url: string) => void
}) {
const pageRoute = getCurrentPages().at(-1)?.route || ''
uni.$lcb.loadingStore?.().changeLoading(pageRoute, true)
const { uploadUrl, ossType, fileUrl } = await uploadByUrl(`${new Date().getTime()}_${name}`)
const fun = (fileData: any) => {
uni.request({
url: uploadUrl,
method: 'PUT',
data: fileData,
header:
ossType === 'tyyun'
? {
'x-amz-acl': 'public-read',
'Content-Type': 'image',
}
: {
'Content-Type': ' ',
},
success: () => {
onSuccess?.(fileUrl)
if (data) data.value = fileUrl
uni.$lcb.loadingStore?.().changeLoading(pageRoute, false)
},
fail: () => {
uni.showToast({
title: '上传失败',
icon: 'none',
})
uni.$lcb.loadingStore?.().changeLoading(pageRoute, false)
},
})
}
// #ifdef H5
fun(await (await fetch(filePath)).arrayBuffer())
// #endif
// #ifndef H5
const fs = uni.getFileSystemManager()
fs.readFile({
filePath,
success: (fileRes) => {
fun(fileRes.data)
},
fail: () => {
uni.showToast({
title: '上传失败',
icon: 'none',
})
uni.$lcb.loadingStore?.().changeLoading(pageRoute, false)
},
})
// #endif
}