ykt-wxapp/utils/file.js

63 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2026-01-21 13:37:54 +08:00
const env = __VITE_ENV__;
2026-01-21 15:27:18 +08:00
export async function uploadFile(tempFilePath) {
2026-01-21 13:37:54 +08:00
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;
2026-01-21 15:27:18 +08:00
if (data && data.success && data.filePath) {
return `${env.MP_API_BASE_URL}${data.filePath}`;
2026-01-21 13:37:54 +08:00
}
} 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'],
2026-01-21 15:27:18 +08:00
sourceType = ['album', 'camera']
2026-01-21 13:37:54 +08:00
} = 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 {
2026-01-21 15:27:18 +08:00
const uploadRes = await uploadFile(tempFilePath);
2026-01-21 13:37:54 +08:00
if (uploadRes) {
return uploadRes;
}
return null;
} catch (e) {
return null;
}
}