39 lines
1.2 KiB
JavaScript
39 lines
1.2 KiB
JavaScript
// utils/media.js — 选图 + 压缩 + 上传云存储,返回 fileID
|
||
// 用法:const fileID = await chooseAndUpload('avatars')
|
||
|
||
/**
|
||
* 选择一张图片(已压缩)并上传到云存储。
|
||
* @param {string} prefix 云存储目录前缀,如 'avatars' / 'walk-photos'
|
||
* @returns {Promise<string|null>} fileID(cloud://...)或 null
|
||
*/
|
||
function chooseAndUpload(prefix = 'uploads') {
|
||
return new Promise((resolve) => {
|
||
wx.chooseMedia({
|
||
count: 1,
|
||
mediaType: ['image'],
|
||
sizeType: ['compressed'],
|
||
sourceType: ['album', 'camera'],
|
||
success: async (r) => {
|
||
const temp = r.tempFiles && r.tempFiles[0] && r.tempFiles[0].tempFilePath;
|
||
if (!temp) return resolve(null);
|
||
wx.showLoading({ title: '上传中', mask: true });
|
||
try {
|
||
const up = await wx.cloud.uploadFile({
|
||
cloudPath: `${prefix}/${Date.now()}-${Math.floor(Math.random() * 1e6)}.jpg`,
|
||
filePath: temp,
|
||
});
|
||
resolve(up.fileID);
|
||
} catch (e) {
|
||
wx.showToast({ title: '上传失败', icon: 'none' });
|
||
resolve(null);
|
||
} finally {
|
||
wx.hideLoading();
|
||
}
|
||
},
|
||
fail: () => resolve(null),
|
||
});
|
||
});
|
||
}
|
||
|
||
module.exports = { chooseAndUpload };
|