unibest/src/hooks/useUpload.ts
杨扬 1e9f73c4f3 fix(upload): 修正环境变量baseUrl配置以区分小程序端环境
修正了useUpload钩子中的baseUrl配置,通过新引入的getEvnBaseUploadUrl方法动态区分不同环境下的基准上传地址。该方法会根据小程序的环境版本(develop、trial、release)返回对应的上传地址,确保上传功能在不同环境下的正确运行。
2024-09-11 20:25:44 +08:00

70 lines
2.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// TODO: 别忘加更改环境变量的 VITE_UPLOAD_BASEURL 地址。
import { getEvnBaseUploadUrl } from '@/utils'
const VITE_UPLOAD_BASEURL = `${getEvnBaseUploadUrl()}`
/**
* useUpload 是一个定制化的请求钩子,用于处理上传图片。
* @param formData 额外传递给后台的数据,如{name: '菲鸽'}。
* @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。
*/
export default function useUpload<T = string>(formData: Record<string, any> = {}) {
const loading = ref(false)
const error = ref(false)
const data = ref<T>()
const run = () => {
// #ifdef MP-WEIXIN
// 微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。
// 微信小程序在2023年10月17日之后使用本API需要配置隐私协议
uni.chooseMedia({
count: 1,
mediaType: ['image'],
success: (res) => {
loading.value = true
const tempFilePath = res.tempFiles[0].tempFilePath
uploadFile<T>({ tempFilePath, formData, data, error, loading })
},
fail: (err) => {
console.error('uni.chooseMedia err->', err)
error.value = true
},
})
// #endif
// #ifndef MP-WEIXIN
uni.chooseImage({
count: 1,
success: (res) => {
loading.value = true
const tempFilePath = res.tempFilePaths[0]
uploadFile<T>({ tempFilePath, formData, data, error, loading })
},
fail: (err) => {
console.error('uni.chooseImage err->', err)
error.value = true
},
})
// #endif
}
return { loading, error, data, run }
}
function uploadFile<T>({ tempFilePath, formData, data, error, loading }) {
uni.uploadFile({
url: VITE_UPLOAD_BASEURL,
filePath: tempFilePath,
name: 'file',
formData,
success: (uploadFileRes) => {
data.value = uploadFileRes.data as T
},
fail: (err) => {
console.error('uni.uploadFile err->', err)
error.value = true
},
complete: () => {
loading.value = false
},
})
}