ykt-wxapp/utils/file.js

63 lines
1.4 KiB
JavaScript
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.

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;
}
}