Files
Pet3/miniprogram/utils/media.js
2026-06-25 18:24:29 +08:00

39 lines
1.2 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.
// utils/media.js — 选图 + 压缩 + 上传云存储,返回 fileID
// 用法const fileID = await chooseAndUpload('avatars')
/**
* 选择一张图片(已压缩)并上传到云存储。
* @param {string} prefix 云存储目录前缀,如 'avatars' / 'walk-photos'
* @returns {Promise<string|null>} fileIDcloud://...)或 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 };