63 lines
1.4 KiB
JavaScript
63 lines
1.4 KiB
JavaScript
const env = __VITE_ENV__;
|
||
|
||
export async function uploadFile(tempFilePath) {
|
||
try {
|
||
const res = await new Promise((resolve, reject) => {
|
||
uni.uploadFile({
|
||
url: `${env.MP_API_BASE_URL}/upload`,
|
||
filePath: tempFilePath,
|
||
name: 'file',
|
||
success: (resp) => resolve(resp),
|
||
fail: (err) => reject(err),
|
||
});
|
||
});
|
||
|
||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||
if (data && data.success && data.filePath) {
|
||
return `${env.MP_API_BASE_URL}${data.filePath}`;
|
||
}
|
||
} 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']
|
||
} = 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;
|
||
}
|
||
try {
|
||
const uploadRes = await uploadFile(tempFilePath);
|
||
if (uploadRes) {
|
||
return uploadRes;
|
||
}
|
||
return null;
|
||
} catch (e) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
|