76 lines
1.9 KiB
JavaScript
76 lines
1.9 KiB
JavaScript
const env = __VITE_ENV__;
|
||
|
||
export async function uploadFile(tempFilePath, businessType, accessLevel = 'public') {
|
||
try {
|
||
const res = await new Promise((resolve, reject) => {
|
||
uni.uploadFile({
|
||
url: `${env.MP_API_BASE_URL}/upload`,
|
||
filePath: tempFilePath,
|
||
name: 'file',
|
||
formData: { businessType, accessLevel },
|
||
success: (resp) => resolve(resp),
|
||
fail: (err) => reject(err),
|
||
});
|
||
});
|
||
|
||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||
if (data && data.success) {
|
||
return data.data;
|
||
}
|
||
} catch (e) {
|
||
console.log('upload file error:', e);
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
/**
|
||
* 选择单张图片并上传,成功返回上传结果(接口返回的 data.data)
|
||
* - 内部会处理 loading / toast
|
||
* - 失败或取消返回 null
|
||
*/
|
||
export async function chooseAndUploadImage(options = {}) {
|
||
const {
|
||
count = 1,
|
||
sizeType = ['compressed'],
|
||
sourceType = ['album', 'camera'],
|
||
businessType = 'other',
|
||
accessLevel = 'public',
|
||
loadingTitle = '上传中...',
|
||
successToast = '上传成功',
|
||
failToast = '上传失败',
|
||
} = options;
|
||
|
||
const imageResult = await new Promise((resolve) => {
|
||
uni.chooseImage({
|
||
count,
|
||
sizeType,
|
||
sourceType,
|
||
success: (res) => resolve(res),
|
||
fail: () => resolve(null),
|
||
});
|
||
});
|
||
|
||
const tempFilePath = imageResult?.tempFilePaths?.[0];
|
||
if (!tempFilePath) {
|
||
return null;
|
||
}
|
||
|
||
uni.showLoading({ title: loadingTitle });
|
||
try {
|
||
const uploadRes = await uploadFile(tempFilePath, businessType, accessLevel);
|
||
uni.hideLoading();
|
||
if (uploadRes) {
|
||
uni.showToast({ title: successToast, icon: 'success' });
|
||
return uploadRes;
|
||
}
|
||
uni.showToast({ title: failToast, icon: 'none' });
|
||
return null;
|
||
} catch (e) {
|
||
uni.hideLoading();
|
||
uni.showToast({ title: failToast, icon: 'none' });
|
||
return null;
|
||
}
|
||
}
|
||
|
||
|