Files
uniapp-im-shop/utils/media.js
2026-01-07 00:52:23 +08:00

46 lines
1.3 KiB
JavaScript
Raw Permalink 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.
/**
* 封装 uni.chooseImage返回 Promise便于 async/await 使用
* @param {Object} options - 透传给 uni.chooseImage 的配置
* @returns {Promise<Array<string>>} 返回选中的临时图片路径数组
*/
export const chooseImage = (options = {}) => {
// 默认配置
const defaultOptions = {
count: 1,
sourceType: ['album', 'camera'],
...options
}
return new Promise((resolve, reject) => {
uni.chooseImage({
...defaultOptions,
success(res) {
if (res.tempFilePaths && res.tempFilePaths.length > 0) {
resolve(res.tempFilePaths)
} else {
reject(new Error('未选择任何图片'))
}
},
fail(err) {
// 统一错误处理(如权限被拒、用户取消等)
let msg = '选择图片失败'
if (err.errMsg.includes('cancel')) {
msg = '用户取消选择'
} else if (
err.errMsg.includes('auth deny') ||
err.errMsg.includes('permission')
) {
msg = '请在设置中开启相册或相机权限'
}
// 可选:自动弹出 toast 提示
uni.showToast({
title: msg,
icon: 'none',
duration: 2000
})
reject(new Error(msg))
}
})
})
}