以Promise风格调用: 支持
拍摄或从手机相册中选择图片或视频。
属性 | 类型 | 默认值 | 必填 | 说明 |
|---|---|---|---|---|
| count | number | 否 | 最多可以选择的图片张数,默认9 | |
| mediaType | array | image,video | 否 | 文件类型,可选值有image、video、mix。如果要实现互斥选择,可以传入image、video |
| sourceType | array | album,camera | 否 | 图片和视频选择的来源 |
| maxDuration | number | 10 | 否 | 拍摄视频最长拍摄时间,单位秒。时间范围为 3s 至 60s 之间。不限制相册。 |
| sizeType | array | original,compressed | 否 | 是否压缩所选文件,可选值为original、compressed |
| camera | string | 否 | 仅在 sourceType 为 camera 时生效,使用前置或后置摄像头 | |
| success | function | 否 | 接口调用成功的回调函数 | |
| fail | function | 否 | 接口调用失败的回调函数 | |
| complete | function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
值 | 说明 |
|---|---|
| front | 使用前置摄像头 |
| back | 使用后置摄像头 |
属性 | 类型 | 说明 |
|---|---|---|
| tempFiles | array | |
| type | string | |
| errMsg | string | chooseMedia:ok |
合法值 | 说明 |
|---|---|
| image | 图片 |
| video | 视频 |
| mix | 图片和视频 |
function chooseMedia(options = {}) {
return new Promise((resolve, reject) => {
xhs.chooseMedia({
...options,
success: (res) => resolve(res),
fail: (err) => reject(err),
});
});
}
// 调用示例
chooseMedia({
count: 5, // 最多选择 5 个文件
mediaType: ['image', 'video'], // 支持图片和视频
sourceType: ['album', 'camera'], // 来源为相册和相机
maxDuration: 15, // 拍摄视频最长 15 秒
sizeType: ['original', 'compressed'], // 支持原图和压缩图
camera: 'back', // 使用后置摄像头
})
.then((res) => {
console.log('选择成功:', res);
res.tempFiles.forEach((file) => {
console.log('文件路径:', file.tempFilePath);
console.log('文件大小:', file.size);
});
console.log('文件类型:', res.type); // image 或 video
})
.catch((err) => {
console.error('选择失败:', err);
});